根据节点内容匹配和更新节点

时间:2017-04-11 10:45:11

标签: mongodb

{
    "doc_id": 1234,
    "pars": [
      {
        "par_id": 4567,
        "someNode": "...",
        "lines": [
          {
            "line_id": 8901,
            "someOtherNode": "...",
            "text": "Foo"
          }, 
        ]
      }
    ]
}

如何更新知道textdoc_idpar_id的正确节点中的line_id字段?

我无法使用此查询,因为我没有与par_idline_id对应的节点索引

con.db.col.update(
    {'_id': doc_id},
    {'$set': { "pars.?.lines.?.text": "Bar" } }
)

3 个答案:

答案 0 :(得分:0)

Because updating based on a match in nested arrays is not yet supported in MongoDB,您需要重新排列架构。现在你有一个段落数组,每个段落都是一个行数组。我建议将段落设为文档,其字段名为paragraphIds,而不是数组。您可以将这些行保存为数组,然后可以使用"$" positional operator通过paragraphId和lineId进行更新:

> db.collection.insertOne({
...   "doc_id": 1234,
...   "pars": {
...     4567: {
...       "someNode": "...",
...       "lines": [
...         {
...           "line_id": 8901,
...           "someOtherNode": "...",
...           "text": "Foo"
...         },
...       ]
...     }
...   }
... })
{
    "acknowledged" : true,
    "insertedId" : ObjectId("58ecb95e475838c0db6efd9d")
}
> db.collection.updateOne({
...   "doc_id": 1234,
...   "pars.4567.lines.line_id": 8901
... }, {
...   "$set": {"pars.4567.lines.$.text": "Bar"}
... })
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
> db.collection.findOne({"doc_id": 1234})
{
  "_id" : ObjectId("58ecb95e475838c0db6efd9d"),
  "doc_id" : 1234,
  "pars" : {
    "4567" : {
      "someNode" : "...",
      "lines" : [
        {
          "line_id" : 8901,
          "someOtherNode" : "...",
          "text" : "Bar"
        }
      ]
    }
  }
}

答案 1 :(得分:-1)

你可以做这样的事情 -

db.col.update(
    {"_id": doc_id, "par_id": 4567,  "pars.lines.line_id":8901},
    {$set: { "pars.$.lines.$.text":"ANY_TEXT_YOU_WANT" } },
function(){}  //callback function)

答案 2 :(得分:-1)

$$是特殊运算符(新位置运算符)

你可以做这样的事情 -

db.col.update(
    {"_id": doc_id, "par_id": 4567,  "pars.lines.line_id":8901},
    {$set: { "pars.lines.$$.text":"ANY_TEXT_YOU_WANT" } },
function(){}  //callback function)