Reputation: 2992
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.
Upvotes: 11
Views: 20699
Reputation: 20703
db.collection.update({'_id':'abc'},{$set:{field1:1,field2:2}},{upsert:true})
should do what you want:
{_id:'abc',field1:1,field2:2}
and efficiently so, since an index is used which must existSince 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.
Upvotes: 15