Azure Cosmos DB for MongoDB vCore 中的 $[identifier] 数组更新运算符用于更新与给定条件匹配的数组中的特定元素。 当需要根据特定条件更新数组中的多个元素时,此运算符特别有用。 它允许在文档中进行更精细的更新,使其成为管理复杂数据结构的强大工具。
javascript
{
"<update operator>": {
"<array field>.$[<identifier>]": <value>
}
},
{
"arrayFilters": [
{ "<identifier>.<field>": <condition> }
]
}
参数
参数 | DESCRIPTION |
---|---|
<update operator> |
要应用的更新运算符(例如 $set , $inc 等)。 |
<array field> |
包含要更新的数组的字段。 |
<identifier> |
用于 arrayFilters 匹配数组中特定元素的占位符。 |
<value> |
要设置或更新的值。 |
arrayFilters |
用于标识要更新的元素的筛选器条件数组。 |
<field> |
要检查的数组元素中的特定字段。 |
<condition> |
数组元素必须满足的条件才能更新。 |
示例
示例 1:更新特定类别的折扣百分比
假设你想要在“假日特别”促销活动中更新“笔记本电脑”类别的折扣百分比。
db.collection.update(
{ "store.storeId": "12345", "store.promotionEvents.eventName": "Holiday Specials" },
{
$set: {
"store.promotionEvents.$[event].discounts.$[discount].discountPercentage": 18
}
},
{
arrayFilters: [
{ "event.eventName": "Holiday Specials" },
{ "discount.categoryName": "Laptops" }
]
}
)
示例 2:按类别增加总销售额
假设你想要将“智能手机”类别的总销售额增加 10,000 美元。
db.collection.update(
{ "store.storeId": "12345" },
{
$inc: {
"store.sales.salesByCategory.$[category].totalSales": 10000
}
},
{
arrayFilters: [
{ "category.categoryName": "Smartphones" }
]
}
)