MongoDB查询中的条件必选$inc



我有一个调查系统,里面有这样的文档:

{
    "_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在这个数组内为一个特定的文档?我尝试了这个查询(基于这个网站),但它没有工作:

db.bigsurveys.update(
   {_id: ObjectId('555b0b33ed26911e080102c4'), 'answers.$.code' : 'opt1'}, 
   { $inc : { 'answers.$.votes' : 1 } }
)

这里的主要问题是我可以有多个这样的文档。提前感谢!

使用$elemMatch和位置运算符$来更新查询:

db.bigsurveys.update({
   "_id": ObjectId("555b0b33ed26911e080102c4"),
   "answers": {
     "$elemMatch": {
       "code": "opt1"
     }
   }
 }, {
   "$inc": {
     "answers.$.votes": 1
   }
 })

最新更新