3

I have a document with a field called info, and info has a field inside it called data. data is an array of objects. I want to add a new boolean field, isActive: false, to each object in data, with updateMany.

This is how it looks now

{ 
    info: {
        data: [{
                "name": "Max"
            },
            {
                "name": "Brian"
            },
            ...
        ]
    }
}

This is what I want:

{ 
    info: {
        data: [{
                "name": "Max",
                "isActive": false
            },
            {
                "name": "Brian",
                "isActive": false
            },
            ...
        ]
    }
}

How do I do that?

2
  • This query is for querying or updating documents? Commented Jul 25, 2022 at 12:19
  • @YongShun updating Commented Jul 25, 2022 at 12:20

2 Answers 2

10

Add the isActive field with all positional operator $[].

db.collection.update({},
{
  $set: {
    "info.data.$[].isActive": false
  }
},
{
   multi: true
})

Consider applying { multi: true } if you want to update multiple documents.

Sign up to request clarification or add additional context in comments.

3 Comments

instead of multi: true is it possible to use updateMany? Because I'm already doing other things using updateMany, so I could just put the query within that script?
If I not mistaken, .updateMany() is for Mongoose. The { multi: true } is equivalent to .updateMany() in Mongoose. Because I'm already doing other things using updateMany, so I could just put the query within that script?, it depends on what is the data and query that you used currently.
update is now giving a deprecation warning so it seems that the updateMany answer will be more appropriate in the future
2

UpdateMany is also possible, for example in Compass.

db.collection.updateMany({"info.data.isActive":{$exists:false}},{$set:"info.data.$[].isActive":false}})

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.