I'd like to know how to update the "value" field of one of the elements identified by the "name" field in the array "array_of_stuff". For example, I want to update the value for "name_of_thing_1" to "new_value_of_thing_1". How can I do this ONLY using the second parameter (i.e. the update parameter) to the update command. I am re-using a class library written in-house I don't have control over the first argument to the update command (i.e. the query parameter). Is this possible?
{
"array_of_stuff": [
{
"name": "name_of_thing_1",
"value": "value_of_thing_1",
},
{
"name": "name_of_thing_2",
"value": "value_of_thing_2",
}
]
}
Thanks for your help!
3 Answers 3
You can update the value of a single item in an array (if you know its index) like this:
db.stuff.update(/* query ... */, {$set:{"arrayname.<index>":new_value}})
If your array contains documents, you can update a particular field of a document at that index like this:
db.stuff.update(/* query ... */, {$set:{"array_of_stuff.0.value":"new_value_of_thing_1"}})
// If you could use the query parameter and knew something
// about the value in the array you wanted to change:
db.stuff.update({"array_of_stuff.value":"value_of_thing_1"}, {$set:{"array_of_stuff.$.value":"new_value_of_thing_1"}})
Comments
See if this example help you:
db.bruno.insert({"array": [{"name": "Hello", "value": "World"}, {"name": "Joker", "value": "Batman"}]})
db.bruno.update({"array.name": "Hello"}, {$set: {"array.$.value": "Change"}})
db.bruno.find().pretty()
output:
db.bruno.find().pretty()
{
"_id" : ObjectId("52389faaafd72821e7b25a73"),
"array" : [
{
"name" : "Hello",
"value" : "Change"
},
{
"name" : "Joker",
"value" : "Batman"
}
]
}
Comments
I don't think it is possible. In order to update field of one of the elements in array, you should use positional $ operator, e.g.:
update({'array_of_stuff.name':'name_of_thing_1'},
{ $set: {'array_of_stuff.$.value':'new_value_of_thing_1'}})
But according to documentation: positional $ operator acts as a placeholder for the first element that matches query document, and the array field must appear as part of the query document.