2014-02-11 46 views
0

我有一个像以下数据:更新不适用于空值?

{ 
    title: "whatever" 
    answers:[ 
     { 
     "question_id" : 11294, 
     "sub_id" : null, 
     "_id" : ObjectId("52f90f68bab16dd8595d453e"), 
     "values" : [ 
     "Po " 
     ] 
     } 
    ] 
} 

,我试图像这样来更新它:

db.participants.update(
    { 
     "answers.question_id": 11294, 
     "answers.sub_id": null 
    }, 
    { 
     $set: 
     { 
      "answers.$.question": 'test' 
     } 

    }, 
    false, 
    true 
); 

但它不工作(未更新的记录)。如果有sub_idanswers.sub_id的值,那么更新工作正常。我该如何编写此更新,以便它们在更新记录时都具有answers.sub_id的值,并且answers.sub_id为空?

UPDATE:

之前,我运行查询,然后它删除后,我创建这个索引:

db.participants.ensureIndex({"answers.question_id": 1, "answers.sub_id": 1}); 
+0

该查询对我来说看起来是正确的。还在我的机器上测试过它(mongodb 2.5.4)。 – mnemosyn

+0

哦,很奇怪..你定义用'null_id'的空值测试过吗? –

+0

看起来我正在运行'2.4.1'我想知道这是否会有所作为? –

回答

1

你应该尝试$elemMatch

db.participants.update(
    { 
     answers: {$elemMatch: {"question_id": 11294, "sub_id": null}} 
    }, 
    { 
     $set: 
     { 
      "answers.$.question": 'test' 
     } 

    }, 
    false, 
    true 
); 

的 “答案” 场在你的例子中是一个数组,而不是一个子文档。希望这可以帮助。