Mongodb $inc 嵌入值语法
我正在尝试使用 $inc 运算符增加 mongodb 文档中的字段。我试图增加的字段是我的文档计数字段的子属性,例如:
mydoc: {
count: {
schedules: 0
}
}
当我尝试这样做时:
> db.mydocs.update({ _id: new ObjectId('4db5c2f3dc73c5afdaffd636') }, { $inc: { count.schedules: 1 } }, { upsert: true, safe: true }, null);
从我的 mongo shell 中,我收到此错误消息:
Mon Apr 25 11:59:05 SyntaxError: missing : after property id (shell):1
我尝试了几种具有类似结果的语法变体。我需要采取不同的方法吗?我已经验证我的文档存在并且有一个设置为 0 的 count.schedules 字段。
我可以使用如下命令直接设置该值:
db.mydocs.update({ _id: new ObjectId('4db5c2f3dc73c5afdaffd636') }, { $set: { count: { schedules:1 } } }, null, null);
但是如果我尝试使用该语法进行 $inc 操作,我会收到此错误:
Modifier $inc allowed for numbers only
谢谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,您只能对数字执行
$inc
。以下是我尝试重现您的问题的方法,您可以注意到我使用了正确的引号,这就是您看到missing : after property id(shell):1
错误的原因。希望这有帮助!
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 themissing : after property id(shell):1
error.Hope this helps!
我认为这可能是一个简单的修复。尝试在
count.schedules
周围加上引号,如下所示:I think this may be a simple fix. Try putting quotes around
count.schedules
like so: