MongoDB 查询中的条件 $inc
Conditional $inc in MongoDB query
我有一个调查系统,其中包含这样的文件:
{
"_id" : ObjectId("555b0b33ed26911e080102c4"),
"question" : "survey",
"subtitle" : "",
"answers" : [
{
"title" : "option 1",
"color" : "#FFEC00",
"code" : "opt1",
"_id" : ObjectId("555b0b33ed26911e080102ce"),
"votes" : 0,
"visible" : true
},
{
"title" : "option 2",
"color" : "#0bb2ff",
"code" : "opt2",
"_id" : ObjectId("555b0b33ed26911e080102cd"),
"votes" : 0,
"visible" : true
}
]
}
现在,我正在提交投票,因此我需要为特定调查增加 'votes' 字段(取决于用户选择的选项)。
我的问题是:我可以有多个这样的文档,所以 我如何 $inc
在此数组中为特定文档字段 votes
?我尝试了这个查询(基于 this website),但没有成功:
db.bigsurveys.update(
{_id: ObjectId('555b0b33ed26911e080102c4'), 'answers.$.code' : 'opt1'},
{ $inc : { 'answers.$.votes' : 1 } }
)
这里的主要问题是我可以有多个这样的文档。提前致谢!
使用 $elemMatch and postional operator $ 将查询更新为:
db.bigsurveys.update({
"_id": ObjectId("555b0b33ed26911e080102c4"),
"answers": {
"$elemMatch": {
"code": "opt1"
}
}
}, {
"$inc": {
"answers.$.votes": 1
}
})
我有一个调查系统,其中包含这样的文件:
{
"_id" : ObjectId("555b0b33ed26911e080102c4"),
"question" : "survey",
"subtitle" : "",
"answers" : [
{
"title" : "option 1",
"color" : "#FFEC00",
"code" : "opt1",
"_id" : ObjectId("555b0b33ed26911e080102ce"),
"votes" : 0,
"visible" : true
},
{
"title" : "option 2",
"color" : "#0bb2ff",
"code" : "opt2",
"_id" : ObjectId("555b0b33ed26911e080102cd"),
"votes" : 0,
"visible" : true
}
]
}
现在,我正在提交投票,因此我需要为特定调查增加 'votes' 字段(取决于用户选择的选项)。
我的问题是:我可以有多个这样的文档,所以 我如何 $inc
在此数组中为特定文档字段 votes
?我尝试了这个查询(基于 this website),但没有成功:
db.bigsurveys.update(
{_id: ObjectId('555b0b33ed26911e080102c4'), 'answers.$.code' : 'opt1'},
{ $inc : { 'answers.$.votes' : 1 } }
)
这里的主要问题是我可以有多个这样的文档。提前致谢!
使用 $elemMatch and postional operator $ 将查询更新为:
db.bigsurveys.update({
"_id": ObjectId("555b0b33ed26911e080102c4"),
"answers": {
"$elemMatch": {
"code": "opt1"
}
}
}, {
"$inc": {
"answers.$.votes": 1
}
})