Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb update. setOnInsert Mod on _id not allowed

Tags:

mongodb

I understand the fact that you can't update _id on an existing mongodb document.

But is there a reason that we can't use it in an upsert in the 'setOnInsert' part ? Because it is 'on insert' so it's not an update.

My expected usage is this:

db.myCol.update({_id:12345},{$setOnInsert:{_id:12345},$set:{myValue:'hi'}});

Is this a bug or am i missing something ?

like image 232
Kurt Agius Avatar asked Apr 25 '13 14:04

Kurt Agius


1 Answers

MongoDB uses the 'query' part for an upsert query as part of the set, meaning that you don't have to specify the _id in the set part of you want to specify your own _id.

note: my query above also had a small bug which was the missing upsert flag.

This is the correct query:

db.myCol.update({_id:12345},{$set:{myValue:'hi'}},{upsert:true});

If the record doesn't exist, this query will insert a record which looks like this:

{_id:12345,myValue:'hi'}
like image 51
Kurt Agius Avatar answered Sep 27 '22 19:09

Kurt Agius