Skip to content

Instantly share code, notes, and snippets.

@jmikola
Last active January 2, 2016 10:19
Show Gist options
  • Save jmikola/8289384 to your computer and use it in GitHub Desktop.
Save jmikola/8289384 to your computer and use it in GitHub Desktop.
Upserting identifier-only documents in MongoDB

MongoDB 2.4.8

> db.foo.update({_id:1}, {$set: {}}, true); db.getLastErrorObj();
{
	"updatedExisting" : false,
	"n" : 1,
	"connectionId" : 1,
	"err" : null,
	"ok" : 1
}
> db.foo.update({_id:2}, {}, true); db.getLastErrorObj();
{
	"updatedExisting" : false,
	"upserted" : ObjectId("52cb12553ad84dc22b80c72f"),
	"n" : 1,
	"connectionId" : 1,
	"err" : null,
	"ok" : 1
}
> db.foo.update({_id:3}, {$set: {_id:3}}, true); db.getLastErrorObj();
{
	"err" : "Mod on _id not allowed",
	"code" : 10148,
	"n" : 0,
	"connectionId" : 1,
	"ok" : 1
}
> db.foo.find()
{ "_id" : 1 }
{ "_id" : ObjectId("52cb12553ad84dc22b80c72f") }

MongoDB 2.5.x

> db.foo.update({_id:1}, {$set: {}}, true); db.getLastErrorObj();
{
	"err" : "'$set' is empty. You must specify a field like so: {$mod: {<field>: ...}}",
	"code" : 16840,
	"n" : 0,
	"connectionId" : 2,
	"ok" : 1
}
> db.foo.update({_id:2}, {}, true); db.getLastErrorObj();
{
	"updatedExisting" : false,
	"upserted" : 2,
	"n" : 1,
	"connectionId" : 2,
	"syncMillis" : 0,
	"writtenTo" : null,
	"err" : null,
	"ok" : 1
}
> db.foo.update({_id:3}, {$set: {_id:3}}, true); db.getLastErrorObj();
{
	"updatedExisting" : false,
	"upserted" : 3,
	"n" : 1,
	"connectionId" : 2,
	"syncMillis" : 0,
	"writtenTo" : null,
	"err" : null,
	"ok" : 1
}
> db.foo.find()
{ "_id" : 2 }
{ "_id" : 3 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment