Reputation: 411
Lets say I have a document like this
{ "_id" : ObjectId("544946347db27ca99e20a95f"), "name" : "Foo Bar",'firstName':"foo", "lastName":"bar" }
If I perform two separate updates like this
update({'_id':'544946347db27ca99e20a95f'},{$set:{'lastName':'BARBAR'}})
update({'_id':'544946347db27ca99e20a95f'},{$set:{'name':'Foo BARBAR'}})
Is it like two separate transactions or does it aggregate both of them and do a single write?
If I have to learn more about the internal workings, what should I be searching for?
Thank you for your help.
Upvotes: 3
Views: 1378
Reputation: 61225
It is two different update operations.
In almost all MongoDB Operators you can use many fields. So the best way is:
db.collection.update({ '_id':'544946347db27ca99e20a95f'}, {
'$set': { 'lastName': 'BARBAR', 'name': 'Foo BARBAR' }
})
You can learn more about Operators in the official documentation. For example the $set
operator has the following syntax:
{ $set: { <field1>: <value1>, ... } }
You may want to use the "Bulk" API and in this case rewrite your function so that the can take a bulk object argument.
var bulk = db.collection.initializeOrderedBulkOp();
function foo(bulk){
// do something
bulk.find({ "_id": "544946347db27ca99e20a95f" }).updateOne({
"$set": { "lastName": "BARBAR" }
// do another thing
});
}
function bar(bulk){
// do something
bulk.find({ "_id": "544946347db27ca99e20a95f" }).updateOne({
"$set": { "name": "Foo BARBAR" }
// do another thing
});
}
foo(bulk);
bar(bulk);
bulk.execute();
Upvotes: 1