Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongodb update with upsert:true does not act as in insert

Tags:

mongodb

I am trying to use update with upsert whiwle providing my own _id as key.

As it turns out, it works only when I use insert, if upsert:true is provided with the update, the new inserted doc gets Mongo's auto-generated id.

See bellow:

PRIMARY> db.internal.update({_id: "my_id"},{ "value": "xyz"}, {upsert:true})
PRIMARY> db.internal.find()
{ "_id" : ObjectId("50c6cbb21d8b512bc0fe9576"), "value" : "xyz" }
PRIMARY> db.internal.insert({_id: "my_id2", "value": "xyz"})
PRIMARY> db.internal.find()
{ "_id" : ObjectId("50c6cbb21d8b512bc0fe9576"), "value" : "xyz" }
{ "_id" : "my_id2", "value" : "xyz" }

Is this a feature or a bug?

According to what I see in Mongo's docs, this shall work

like image 533
Tzury Bar Yochay Avatar asked Jan 14 '23 19:01

Tzury Bar Yochay


1 Answers

Yes, that's a little known gotcha. The trick is to use a $set modifier with the upsert. It will then combine your update and query parts to form the upserted document. Look:

db.internal.update({_id: "my_id"},{"$set": {"value": "xyz"}}, {upsert:true})
db.internal.find()
// { "_id" : "my_id", "value" : "xyz" }
like image 172
Sergio Tulentsev Avatar answered Jan 28 '23 14:01

Sergio Tulentsev