I am new to mongodb.
I have a database like this:
{
"universe": "DC",
"characters": [
{"name": "superman&qu
Starting in MongoDB 3.6, when updating an array field, you can specify arrayFilters that determine which array elements to update.
mydb.collection.findOneAndUpdate(
{
universe: "DC"
},
{
$set : {
"characters.$[has].selected" : true,
"characters.$[not].selected" : false
}
},
{
arrayFilters: [
{
"has.name": { $eq: "wonder woman" }
},
{
"not.name": { $ne: "wonder woman" }
}
],
returnNewDocument: true
}
)
universe
field equals "DC"$[]
with the arrayFilters
to modify the selected
to true
for all elements in the characters
array where the name
(has.name) is $eq
to "wonder women"arrayFilters
to modify the selected
to false
for all elements in the characters
array where the name
(not.name) is $ne
to "wonder women".returnNewDocument: true
return updated document