Mongodb $ inc嵌入值语法

din*_*jas 3 javascript database mongodb node.js

我正在尝试使用$ inc运算符在我的mongodb文档中增加一个字段.我想要增加的字段是我的文档计数字段的子属性,例如:

mydoc: {
    count: {
        schedules: 0
    }
}
Run Code Online (Sandbox Code Playgroud)

当我尝试这个:

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

从我的mongo shell,我收到此错误消息:

Mon Apr 25 11:59:05 SyntaxError: missing : after property id (shell):1
Run Code Online (Sandbox Code Playgroud)

我尝试了几种类似结果的语法变体.我需要采取不同的方法吗?我已经验证了我的文档存在并且有一个count.schedules字段设置为0.

我可以使用如下命令直接设置值:

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

但是,如果我尝试$ inc操作的语法,我会收到此错误:

Modifier $inc allowed for numbers only
Run Code Online (Sandbox Code Playgroud)

谢谢

lob*_*234 5

是的,你只能做$inc数字.以下是我尝试重现您的问题的方法,您可以注意到我使用了正确的引号,这就是您看到missing : after property id(shell):1错误的原因.

> 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 } } }
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!