Bryan Migliorisi
Bryan Migliorisi

Reputation: 9210

Multiple $inc updates in 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?

Upvotes: 23

Views: 9688

Answers (1)

Cameron
Cameron

Reputation: 98746

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 :-)

Upvotes: 51

Related Questions