Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb $inc embedded value syntax

I'm trying to increment a field in my mongodb document using the $inc operator. The field I am trying to increment is a sub-property of my document's count field, e.g.:

mydoc: {
    count: {
        schedules: 0
    }
}

When I try this:

> db.mydocs.update({ _id: new ObjectId('4db5c2f3dc73c5afdaffd636') }, { $inc: { count.schedules: 1 } }, { upsert: true, safe: true }, null);

from my mongo shell, I get this error message:

Mon Apr 25 11:59:05 SyntaxError: missing : after property id (shell):1

I've tried several syntax variations with similar results. Do I need to take a different approach to this? I've verified my document exists and has a count.schedules field that is set to 0.

I can directly set the value using a command like this:

 db.mydocs.update({ _id: new ObjectId('4db5c2f3dc73c5afdaffd636') }, { $set: { count: {  schedules:1 } } }, null, null);

But if I try that syntax for the $inc operation, I get this error:

Modifier $inc allowed for numbers only

Thanks

like image 951
dinjas Avatar asked Apr 02 '26 01:04

dinjas


1 Answers

Yes, you can do a $inc only on numbers. Here is how I tried to reproduce your problem, you can notice I've used proper quotes, which is the reason you are seeing the missing : after property id(shell):1 error.

> db.schedules.save({"mydoc": { "count": { "schedules": 0}}});                                                                                                     
> db.schedules.find();                                         
{ "_id" : ObjectId("4db5cf199e631c2a52a7c643"), "mydoc" : { "count" : { "schedules" : 0 } } }
> db.schedules.update({ _id: new ObjectId("4db5cf199e631c2a52a7c643") }, { $inc: { "mydoc.count.schedules": 1 } }, { upsert: true, safe: true }, null);
> db.schedules.find();                                                                                                                                  
{ "_id" : ObjectId("4db5cf199e631c2a52a7c643"), "mydoc" : { "count" : { "schedules" : 1 } } }

Hope this helps!

like image 77
lobster1234 Avatar answered Apr 03 '26 17:04

lobster1234



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!