0

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?

Yong Shun
  • 35,286
  • 4
  • 24
  • 46
TheStranger
  • 1,387
  • 1
  • 13
  • 35

2 Answers2

4

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.

Yong Shun
  • 35,286
  • 4
  • 24
  • 46
  • 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? – TheStranger Jul 25 '22 at 12:26
  • 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. – Yong Shun Jul 25 '22 at 12:41
0

UpdateMany is also possible, for example in Compass.

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

Mark
  • 1
  • 1