TheStranger
TheStranger

Reputation: 1577

MongoDB - How to add a field to all object within an array

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?

Upvotes: 3

Views: 7455

Answers (2)

Mark
Mark

Reputation: 21

UpdateMany is also possible, for example in Compass.

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

Upvotes: 2

Yong Shun
Yong Shun

Reputation: 51220

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.

Upvotes: 10

Related Questions