2015-05-19 24 views
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 
     } 
    ] 
} 

現在,我正在提交表決,所以我需要提高的投票'字段的具體調查(取決於用戶選擇的選項)。

我的問題是:我可以有多個文件那樣的,所以我怎麼可以$inc字段votes這個數組裏面有一個特定的文件?我嘗試這個查詢(基於this website),但它沒有工作:

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

這裏的主要問題是,我可以有多個文檔這樣的。提前致謝!

回答

2

使用$elemMatch和postional操作$更新查詢爲:

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

這正是我一直在尋找。感謝yogesh! –