$[<identifier>]
The `$[<identifier>]` array update operator is used to update specific elements in an array that match a given condition. This operator is useful when you need to update multiple elements within an array based on certain criteria. It allows for more granular updates within documents, making it a powerful tool for managing complex data structures.
Syntax
{
<update operator>: {
<array field>.$[<identifier>]: <value>
}
},
{
arrayFilters: [
{ <identifier>.<field>: <condition> }
]
}
Parameters
<update operator>
stringrequiredThe update operator to be applied (for example, $set, $inc, etc.).
<array field>
stringrequiredThe field containing the array to be updated.
<identifier>
stringrequiredA placeholder used in arrayFilters to match specific elements in the array.
<value>
stringrequiredThe value to be set or updated.
arrayFilters
objectrequiredAn array of filter conditions to identify which elements to update.
<field>
stringrequiredThe specific field within array elements to be checked.
<condition>
stringrequiredThe condition that array elements must meet to be updated.
Examples
Sample Data
{
"_id": "905d1939-e03a-413e-a9c4-221f74055aac",
"name": "Trey Research | Home Office Depot - Lake Freeda",
"promotionEvents": [
{
"eventName": "Blowout Bonanza",
"discounts": [
{ "categoryName": "Office Chairs", "discountPercentage": 24 },
{ "categoryName": "Desk Lamps", "discountPercentage": 19 }
]
}
]
}
Update the discount percentage for the chosen category in the specified promotion event
Updates the discount percentage for Desk Lamps category by modifying specific elements in the promotion event array where the event name is Blowout Bonanza.
Query:
db.stores.updateOne(
{
_id: "905d1939-e03a-413e-a9c4-221f74055aac",
"promotionEvents.eventName": "Blowout Bonanza"
},
{
$set: {
"promotionEvents.$[event].discounts.$[discount].discountPercentage": 18
}
},
{
arrayFilters: [
{ "event.eventName": "Blowout Bonanza" },
{ "discount.categoryName": "Desk Lamps" }
]
}
)