开发者

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


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!


I think this may be a simple fix. Try putting quotes around count.schedules like so:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜