4

How to update some of the nested objects found by thair Id in MongoDB.

In the below case, only the first Item will be updated!

Update all nested objects in updateMany.

"Parent":[{
        "Child": [{
                "_id": 5f26fad5b34a304dfc1dd16a,
                "isActive": false,                    
            }, {
                "_id": 5f26fad5b34a304dfc1dd16c,
                "isActive": false,                    
            }, {
                "_id": 5f2705281b42ea2de8b7c9e2,
                "isActive": false,                    
            } 
        ],
        "name": "Paretn1"
    },  
]



    parent.updateMany(
    { 
      "child._id": { $in: [ObjectId('5f26fad5b34a304dfc1dd16a'), ObjectId('5f26fad5b34a304dfc1dd16c') 
    ]} 
    },
    { $set: { "child.$.isActive": true } },
    { multi: true },
    () => {
      console.log('done')
    }
  );

1 Answer 1

4

You can do as below

parent.updateMany(
{ 
   "child._id": { $in: 
              [ObjectId('5f26fad5b34a304dfc1dd16a'), 
              ObjectId('5f26fad5b34a304dfc1dd16c') 
              ]} 
    },
    { $set: { "child.$[element].isActive": true } },
    { "arrayFilters": [{ "elem._id": {'$in' :[  
              ObjectId('5f26fad5b34a304dfc1dd16a'), 
              ObjectId('5f26fad5b34a304dfc1dd16c')] } }], "multi": true }, 
    () => {
        console.log('done')
    }
  );
Sign up to request clarification or add additional context in comments.

1 Comment

This answer worked for me. I had to change [element] to [elem] to match the arrayFilter. Thank You!

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.