Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (4k points)

Can i combine $pushAll and $inc in one statement ?

Before combine, this works fine :

db.createCollection("test");
db.test.insert({"name" : "albert", "bugs" : []});

db.test.update({"name":"albert"}, 
    {"$pushAll" : {"bugs" : [{"name":"bug1", "count":1}]}});

db.test.update({"name":"albert"}, 
    {"$inc" : {"bugs.0.count" : 1}});

db.test.update({"name":"albert"}, 
    {"$pushAll" : {"bugs" : [{"name":"bug2", "count":1}]}});

But when i try combining it like this :

db.createCollection("test");
db.test.insert({"name" : "albert", "bugs" : []});

db.test.update({"name":"albert"}, 
    {"$pushAll" : {"bugs" : [{"name":"bug1", "count":1}]}});

db.test.update({"name":"albert"}, 
    {
       "$pushAll" : {"bugs" : [{"name":"bug2", "count":1}]}, 
       "$inc" : {"bugs.0.count" : 1}
    }
);

This error happens :

have conflicting mods in update

1 Answer

0 votes
by (8.7k points)

It should be taken care that the updates should not conflict with each other while performing multiple updates on the same document.

As the problem is that   "$push" : {"bugs" : [{"name":"bug1", "count":1}]} and "$inc" : {"bugs.0.count" : 1} are parallely trying to update the same section”bugs” array ,therefore they all conflicts.

So this can be achieved if multiple updates are modifying different sections of a document at a particular instance as:

> db.test.drop()

true

> db.test.save({ "_id" : 1, "name" : "albert", "bugs" : [ ] })

> db.test.update({"name":"albert"}, {"$pushAll" : {"bugs" : [{"name":"bug1", "count":1}]}, "$inc" : {"increment" : 1}, $set:{"note":"Here is another field."}})

> db.test.find()

{ "_id" : 1, "bugs" : [ { "name" : "bug1", "count" : 1 } ], "increment" : 1, "name" : "albert", "note" : "Here is another field." }.

For more updates check out the MongoDB tutorial by Intellipaat.

Browse Categories

...