Mondodb update array inside array (embeded) (mongoose/nodejs)

Viewed 25

Hello i'm trying to update an embeded document inside an embeded document.

My "object" looks something like this

 {  
    _id:0,
    fieldOne:"f1",
    fieldTwo : "f2",
    subDocument:[
        {
            _id:0,
            subfieldOne:"f1",
            subfieldTwo:"f2",
            subSubDocument:[
                {
                    _id:0,
                    sub_subfieldOne:"f1",
                    sub_subfieldTwo:"f2"
                }
            ]
        },
    ],
}

afer some resarch i found out that you can update a sub sub array item if you know his position, something like this

await Document.updateOne(
    { "subDocument._id": 0},
    { $set:{"subDocument.0.subsubDocument.0.sub_subfieldOne":"testaroo"} });

howerver if i loop through the arrays like

for(let i = 0;i<subDocument.length;i++){
    for(let j = 0;j<subDocument[i].subSubDocument.length;j++){
     await Document.updateOne(
        { "subDocument._id": 0},
        { $set:{"subDocument."+i+".subsubDocument."+j+".sub_subfieldOne":"testaroo"} });
    }
}

he does not like the string concatenation in the query like this.....is there a way to do it?

1 Answers

After reading your code, I think you are trying to update sub_subfieldOne of all sub documents. If so, you can use $[] operator. It indicates that the update operator should modify all elements in the specified array field:

await Document.updateOne(
  { "subDocument._id": 0},
  { $set:{"subDocument.$[].subsubDocument.$[].sub_subfieldOne": "testaroo"} }
);
Related