简体   繁体   中英

How to update nested array document in mongodb

I have a collection looks like

{
 "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
}

I'm not able to update fields that is of innerBlock array, specially name, status because of nesting. Basically, I wanted to update mentioned fields .Iam already try this query

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

It shows an error given below

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

I'm not sure how to fix it.What can be the query in mongo shell? Thanks.

Only one positional operator available right now with mongoDB. There are opened feature request for that https://jira.mongodb.org/browse/SERVER-831

check the answer https://stackoverflow.com/a/14855633/2066271

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM