Reputation: 16045
Given a collection containing several documents like this one:
{
sku: 'P001'
options: [
{
name: 'Size',
value: 'Large'
},
{
name: 'Color',
value: 'Forest Green'
},
{
name: 'Surface',
value: 'Rubber'
}
]
}
I want to search for 'Forest Green' and replace it with 'Brilliant Green'. I tried this:
Products.update(
{ options: { $elemMatch: { value: 'Forest Green' } } },
{ $set: { 'options.value': 'Brilliant Green' } },
{ multi: true }
)
but I get the following error:
MongoError: cannot use the part (options of options.value) to traverse the element ({options: [ { name: "Size", value: "Large" }, { name: "Color", value: "Forest Green" }, { name: "Surface", value: "Rubber" } ]})
It seems like this should work. What am I doing wrong?
Upvotes: 0
Views: 49
Reputation: 2083
i think you should use $ like this
{ 'options.$.value': 'Brilliant Green' }
The positional $ operator facilitates updates to arrays that contain embedded documents. Use the positional $ operator to access the fields in the embedded documents with the dot notation on the $ operator. For more info about $ positional operator see this link
db.collection.update(
{ <query selector> },
{ <update operator>: { "array.$.field" : value } }
)
Thanks
Upvotes: 1