Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does mongodb update work internally?

Tags:

mongodb

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.

like image 778
Satish Gandham Avatar asked Aug 24 '26 19:08

Satish Gandham


1 Answers

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();
like image 159
styvane Avatar answered Aug 26 '26 16:08

styvane



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!