Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use $add inside the update() function in Mongo?

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,

like image 593
user646584 Avatar asked Dec 27 '22 08:12

user646584


1 Answers

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}})
like image 171
dcrosta Avatar answered Jan 08 '23 03:01

dcrosta