Search code examples
mongodbmongodb-querynosqlmongodb-update

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?


Solution

  • 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.