Mongodb:更改嵌套数组中键的值

时间:2017-01-15 15:07:42

标签: mongodb

我有以下数据结构(简化):

{
quiz_id : ObjectId(),
questions : [{
      question : "xyz",
      options : [{
           option_text : "a"
           },
           {
           option_text : "b"
           }]
      }, {
      question : "pqr",
      options : [{
           option_text : "s"
           },
           {
           option_text : "t"
           }]
      }]
}          

现在我想通过向每个选项添加answer_count : 0来添加更新。 所以新的数据结构是:

{
quiz_id : ObjectId(),
questions : [{
      question : "xyz",
      options : [{
           option_text : "a",
           answer_count : 0
           },
           {
           option_text : "b",
           answer_count : 0
           }]
      }, {
      question : "pqr",
      options : [{
           option_text : "s",
           answer_count : 0
           },
           {
           option_text : "t",
           answer_count : 0
           }]
      }]
} 

如何在mongodb中执行此操作?

1 个答案:

答案 0 :(得分:0)

您可以遍历所有文档以添加answer_count和使用db.save()来更新文档。

db.foo.find().forEach(function(doc){
    for(var question of doc.questions) {
        for (var option of question.options) {
            option.answer_count = 0;
        }
    }
    db.foo.save(doc);
})