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?
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.
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.
You cannot update it but you can save a new id and remove the old id.
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 :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With