I'm trying to update this document;
{"dealId" : 201, "commitCount" : 3 }
...I just need to increment commitCount
by 1, so I'm trying to use the add[] function inside update(), but I can't get it to work...
db.deal.update( {dealId:201},{$set:{commitCount:{$add:['$commitCount',1]} }} )
the error I get from Mongo is not okForStorage
, no idea what that means, the field does not get updated,
That error means you're trying to use a field name which is invalid in MongoDB -- that would be either a field name with a dot (".") in it, or a field name containing a dollar sign.
$set
is used to replace a field in its entirety, so what you have above is saying "replace the contents of the commitCount
field with the document {$add: ['$commitCount', 1]}
", which is an invalid document.
To atomically increment or decrement a field's value (assuming the field's current value is a number) use the $inc
modifier:
db.deal.update({dealId: 201}, {$inc: {commitCount: 1}})
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