rowsI am attempting to perform a mongodb update on each field in an array of records.
An example schema is below:
{
"_id" : ObjectId("508710f16dc636ec07000022"),
"summary" : "",
"uid" : "ABCDEF",
"username" : "bigcheese",
"name" : "Name of this document",
"status_id" : 0,
"rows" : [
{
"score" : 12,
"status_id" : 0,
"uid" : 1
},
{
"score" : 51,
"status_id" : 0,
"uid" : 2
}
]
}
So far I have been able to perform single updates like this:
db.mycollection.update({"uid":"ABCDEF","rows.uid":1}, {$set:{"rows.$.status_id":1}},false,false)
However, I am struggling as to how to perform an update that will update all array records to a status_id
of 1 (for instance).
Below is how I imagine it should work:
db.mycollection.update({"uid":"ABCDEF"}, {$set:{"rows.$.status_id":1}},false,true)
However I get the error:
can't append to array using string field name [$]
I have tried for quite a while with no luck. Any pointers?
You can use the updateOne() or updateMany() methods to add, update, or remove array elements based on the specified criteria. It is recommended to use the updateMany() method to update multiple arrays in a collection.
If the value is an array, $push appends the whole array as a single element. To add each element of the value separately, use the $each modifier with $push . For an example, see Append a Value to Arrays in Multiple Documents. For a list of modifiers available for $push , see Modifiers.
In MongoDB, the $push operator is used to appends a specified value to an array. If the mentioned field is absent in the document to update, the $push operator add it as a new field and includes mentioned value as its element. If the updating field is not an array type field the operation failed.
You can't do the sort of 'wildcard' update of array elements that you're looking for. I think the best you can do is simultaneously set each element's status_id
value like this:
db.mycollection.update(
{"uid":"ABCDEF"},
{$set:{
"rows.0.status_id":1,
"rows.1.status_id":1
}}, false, true);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With