Is there a query to update sc from 15 to let's say 17 for array element with id 2 for _id 1? I've this structure in mongodb:
{ _id: 1,
lb: [
{
id: 2,
sc: 15
},
{
id: 3,
sc: 16
}
]
}
{ _id: 2,
lb: [
{
id: 5,
sc: 34
},
{
id: 6,
sc: 12
}
]
}
I have one more: is there a way to write a query to update as you just said and if there is no array element with updated id, insert a new one. I don't want to make two queries - first to check if element exist and update it, second to append it if there is no such. It would be nice to append it in one query. Thanks. – user3045201 1 hour ago
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.
You cannot update it but you can save a new id and remove the old id.
MongoDB provides a few methods for updating data. One of these method is findByIdAndUpdate() method. The findByIdAndUpdate() method matches a single document and then updates it. This method needs a string value, which is the value of the _id field.
You can update it using the following query :
db.myCollection.update({"_id" : 1, "lb.id" : 2},{$set : {"lb.$.sc" : 17}})
AFAIK, It is not possible to do what you want in a single query. You have to make seperate queries for each of them.
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