Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple $inc updates in MongoDB

Tags:

mongodb

Is it possible to update a single document by passing two $inc operators in a single update document?

For example, I am trying to increment two different fields in a given document using the following update document:

{
    "$inc" : { "ViewAggregates.4d75b891842f2d3930cf7674" : 1 },
    "$inc" : { "ViewAggregates.Total" : 1 }
}

No errors are thrown and the document is updated but only one of the fields has been incremented. It is as if the server disregarded the first $inc operator and only the second was actually applied.

Is this the intended\correct behavior or is there something I am missing?

like image 598
Bryan Migliorisi Avatar asked Mar 09 '11 04:03

Bryan Migliorisi


People also ask

What is multi true in MongoDB?

To update multiple documents in a collection, set the multi option to true. multi is optional. If set to true, updates multiple documents that meet the query criteria. If set to false, updates one document.

How do I increment in MongoDB?

In MongoDB, the $inc operator is used to increment the value of a field by a specified amount. The $inc operator adds as a new field when the specified field does not exist, and sets the field to the specified amount. The $inc accepts positive and negative value as an incremental amount.

Can we change _ID in MongoDB?

You cannot update it but you can save a new id and remove the old id.


1 Answers

This is an interesting side-effect of dictionary keys being unique -- the second $inc overwrites the first.

However, it's still possible to increment more than one field:

{
    "$inc": {
        "ViewAggregates.4d75b891842f2d3930cf7674" : 1, 
        "ViewAggregates.Total" : 1
    }
}

This works for many other operators too :-)

like image 103
Cameron Avatar answered Sep 20 '22 01:09

Cameron