如何更新mongodb中的嵌套数组文档

时间:2017-01-20 10:05:29

标签: arrays node.js mongodb mongoose

我有一个类似

的集合
{
 "Aid":12234,
 "items":{
   "itemId":"SP897474",
   "Blocks":[
     {
        "blockId":"W23456",
        "name":"B1",
        "innerBlock":[
           {
              "id":"S23490",
              "name":"IB1",
              "state":true
           },
           {
              "id":"S23491",
              "name":"IB2",
              "state":true
           },
           {
              "id":"S23492",
              "name":"IB3",
              "state":true
           }
        ],
        "active":true
     },
     {
        "blockId":"W23457",
        "name":"B2",
        "innerBlock":[
           {
              "id":"S23482",
              "name":"IB1",
              "state":true
           },
           {
              "id":"S23483",
              "name":"IB2",
              "state":true
           }
        ],
        "active":false
      }
   ]
 },
 "active":true
}

由于嵌套,我无法更新innerBlock数组的字段,特别是名称,状态。基本上,我想更新提到的字段。我已经尝试过这个查询

User.update({
  "items.Blocks.innerBlock.id": req.body.id,
  "Aid": req.body.Aid
}, {
  "$set": {
    "items.Blocks.$.InnerBlock.$.name": req.body.name
  }
})

显示下面给出的错误

"errmsg": "Too many positional (i.e. '$') elements found in path 'items.Blocks.$.InnerBlock.$.name'"

我不知道如何修复它。在mongo shell中可以查询什么?感谢。

1 个答案:

答案 0 :(得分:0)

目前只有一个位置运算符可用于mongoDB。已经打开了https://jira.mongodb.org/browse/SERVER-831

的功能请求

检查答案https://stackoverflow.com/a/14855633/2066271