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
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" }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With