How Can I Update Nested Array Element By Id

I’m new to mongodb , I want to update nested array element by id with findOneAndUpdate

const Data = {
   items : [
      {
       id: 1,
       name : "a",
       child : [
         { id : 11, name "aa"},
         { id : 12, name "bb"},
        ]
      },
      {
       id: 2,
       name : "b",
       child : [
         { id : 22, name "ba"},
         { id : 23, name "bb"},
        ]
      },
    ]
}

Hi @malik_adnan,

This way:

I know already update query , I need the structure, this isn’t solution @MaBeuLux88

It’s exactly the same query that is in the exemple in the deep link I shared I think. If you expect something different, then I didn’t understand your question :/.

Cheers,
Maxime.

Hi @malik_adnan ,

@MaBeuLux88 , I think he needs to use an array filter due to the nested array and not specifically a positional update as it is nested arrays.

For example the following query will update all the “child.name” fields of id: 1 to “cc”:

db.childs.findOneAndUpdate({"items.id" : 1},{$set : {"items.$[t].child.$[].name" : "cc"}},{arrayFilters : [{"t.id" : 1}]})

{ _id: ObjectId("621e22fa63c5b12f4cda3dc0"),
  items: 
   [ { id: 1,
       name: 'a',
       child: [ { id: 11, name: 'cc' }, { id: 12, name: 'cc' } ] },
     { id: 2,
       name: 'b',
       child: [ { id: 22, name: 'ba' }, { id: 23, name: 'bb' } ] } ] }

You can play with additional filters as needed…

Ty
Pavel

2 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.