MongoDB db.collection.save overwrite object if it exists

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

Let define objectToSave as below

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

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

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

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

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

I want to perform the $ set operation to create some document in the collection below

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

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

Note that the objectToSave fields are dynamic. The language I use is Node.JS.

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

should do what you want:

  • It reloads, therefore, if the document does not exist yet, it is created as {_id:'abc',field1:1,field2:2} and is effective, since it uses an index that must exist
  • If the document already exists, the fields field1 and field2 are set to the value in the update instruction.
  • If any of the fields exists in the document, it will be overwritten.

Since you did not indicate which language you are using: plain mongoDB does not have a save function. The explicit requirement to combine new and preserved versions of objects is quite unusual, so yes, I would suggest that you need to write a custom function.

+4
source

Source: https://habr.com/ru/post/1204234/


All Articles