0

simplified schema of a doc in my Model:

{
    ar1: [
        {
            b: {
                ar2: [{ _id: 1, value: 2 }],
            },
        },
        {
            b: {
                ar2: [{ _id: 2, value: 2 }],
            },
        },
        {
            b: {
                ar2: [{ _id: 1, value: 5 }],
            },
        },
    ];
}

now i want to update all elements of ar2 that have _id equal to 1 so I would obtain:

{
    ar1: [
        {
            b: {
                ar2: [{ _id: 1, value: 3 }],
            },
        },
        {
            b: {
                ar2: [{ _id: 2, value: 2 }],
            },
        },
        {
            b: {
                ar2: [{ _id: 1, value: 3 }],
            },
        },
    ];
}

The following does not work:

Model.updateMany({
    'ar1.b.ar2._id' : 1
},{
    'ar1.$[].b.ar2.$[].value' : 2
});

any suggestions ?

The idea is that i want to be able the elements in the nested array that obey the query and update them.

1 Answer 1

1

You can use $[] combine with $[<identifier>] to do that:

Model.update(
  {}, 
  { $set: { "ar1.$[].b.ar2.$[el].value": 3 } },  
  { arrayFilters: [ { "el._id": 1 } ] } 
)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.