Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB db.collection.save overwrite object when existing

Tags:

mongodb

In MongoDB, you can use db.collection.save({_id:'abc'}, objectToSave) to perform an upsert.

Let's define objectToSave as below

{_id:'abc', field1:1, field2:2};

In my collection, I have already have a document with same _id value as below:

{_id:'abc', field3:3};

The save function above will replace the existing document in collection to

{_id:'abc', field1:1, field2:2};

What I want is to perform a $set operation to produce some document in collection as below

{_id:'abc', field1:1, field2:2, field3:3};

Can this be achieved in the save function or I have to write separate update statements?

Note that objectToSave's fields are dynamic. The language I'm using is Node.JS.

like image 569
Lee Avatar asked Oct 08 '14 06:10

Lee


Video Answer


1 Answers

db.collection.update({'_id':'abc'},{$set:{field1:1,field2:2}},{upsert:true})

should do what you want:

  1. It upserts, so if the document does not exist yet, it is created as {_id:'abc',field1:1,field2:2} and efficiently so, since an index is used which must exist
  2. If the document already exists, the fields field1 and field2 are set to the value in the update statement.
  3. If either of the fields exist in the document, it will be overwritten.

Since you didn't state what language you use: in plain mongoDB, there is no save function. The explicit requirement to merge new and persisted versions of entities is quite an unusual one, so yes, I'd assume that you have to write a custom function.

like image 159
Markus W Mahlberg Avatar answered Oct 18 '22 18:10

Markus W Mahlberg