【问题标题】:How to update nested array document in mongodb如何更新 mongodb 中的嵌套数组文档
【发布时间】:2017-06-05 06:43:43
【问题描述】:

我有一个收藏看起来像

{
 "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 中的查询可能是什么?谢谢。

【问题讨论】:

  • 你试过items.Blocks.InnerBlock.name
  • 是的,我试过了。它显示像这样的错误"errmsg": "cannot use the part (innerBlock of "items.Blocks.innerBlock.name) to traverse the element
  • 看看这个答案,我认为它可以帮助update nester array with mongoose
  • 试试这个"items.Blocks[0].InnerBlock[0].name": req.body.name
  • 我在这里找到了解决方案jasonmciver.com/mongo-query-deep-array

标签: arrays node.js mongodb mongoose


【解决方案1】:

mongoDB 目前只有一个位置运算符可用。有针对 https://jira.mongodb.org/browse/SERVER-831 的开放功能请求

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

【讨论】:

    猜你喜欢
    • 2017-04-28
    • 2013-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-23
    • 2016-08-04
    • 2010-11-11
    • 1970-01-01
    相关资源
    最近更新 更多