在一次更新中更新两个子阵列

时间:2013-02-14 13:39:11

标签: mongodb atomic

是否可以通过一次更新更新文档的两个子数组(不检索文档,并使用乐观并发更新它)?

假设我有以下文件:

{ "_id" : 2,
  "arr1" : [
             { "Id" : 10, "Value" : "abc" },
             { "Id" : 20, "Value" : "abc" },
             { "Id" : 30, "Value" : "abc" }, 
             { "Id" : 40, "Value" : "abc" },
             { "Id" : 50, "Value" : "abc" }
           ],
  "arr2" : [
             { "Id" : 12, "Text" : "abc" },
             { "Id" : 22, "Text" : "abc" },
             { "Id" : 32, "Text" : "abc" }, 
             { "Id" : 42, "Text" : "abc" },
             { "Id" : 52, "Text" : "abc" }
           ]
}

我尝试这样做,但似乎没有修改正确的子文档:

db.col.update(
    { "_id": 2, arr1: { $elemMatch: { Id: 30 } }, arr2: { $elemMatch: {Id: 42} } },
    { $set: {
        "arr1.$.Value": "Changed First",
        "arr2.$.Text": "Changed Second"
      }
    })

1 个答案:

答案 0 :(得分:1)

在我看来,如果您的数据看起来像这样,您就可以轻松地执行更新:

{ 
  "_id" : 2,
  "arr1" : {
    "10": "abc",
    "20": "abc",
    "30": "abc",
    "40": "abc",
    "50": "abc"

  }
}