Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update nested array objects based on a property in MongoDB

I have a MongoDB collection which has documents which look like this:

{
    createdTimestamp: 111111111111,
    items: [{
        itemName: 'Name 1',
        quantity: 10
    }, {
        itemName: 'Name 2'
        quantity: 20
    }]
}

Now, I want to update all documents so that itemName: 'Name 1' would be updated to itemName: 'New Name'. After an update, the above document should look like as below:

{
    createdTimestamp: 111111111111,
    items: [{
        itemName: 'New Name',
        quantity: 10
    }, {
        itemName: 'Name 2'
        quantity: 20
    }]
}

Is there any way to do this, without iterating over all documents myself?

like image 548
Lahiru Chandima Avatar asked Oct 17 '25 22:10

Lahiru Chandima


1 Answers

You need to use $ positional operator to update an array element and with multi: true option you can update multiple document with the same match

db.collection.update(
  { 'items': { '$elemMatch': { 'itemName': 'Name 1' }}},
  { '$set': { 'items.$.itemName': 'New Name' }},
  { 'multi': true }
)

and with the mongodb 3.6 arrayFilters

db.collection.update(
  { 'items': { '$elemMatch': { 'itemName': 'Name 1' }}},
  { '$set': { 'items.$[item].itemName': 'New Name' }},
  { 'arrayFilter': [{ 'item.itemName': 'Name 1' }], 'multi': true }
)
like image 69
Ashh Avatar answered Oct 20 '25 16:10

Ashh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!