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?
Hardik Shah
4,2082 gold badges22 silver badges45 bronze badges
asked Jul 31, 2018 at 4:12
Lahiru Chandima
24.4k26 gold badges116 silver badges202 bronze badges
2 Answers 2
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 }
)
answered Jul 31, 2018 at 4:27
Ashh
46.6k16 gold badges111 silver badges137 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Lahiru Chandima
It worked. Had to do a small change:
'$elemMatch': {itemName: 'Name 1'}you can use mongoDb arrayFilters
db.collection.update(
{ },
{ "$set": { "items.$[elem].itemName": 'new Name' } },
{ "arrayFilters": [{ "elem.itemName": 'Name 1' }], "multi": true }
)
turivishal
36.4k7 gold badges48 silver badges69 bronze badges
answered Jul 31, 2018 at 4:34
Amit Wagner
3,1843 gold badges23 silver badges39 bronze badges
Comments
lang-js