DocumentDB 中的 $[] 運算子用於更新陣列中符合指定條件的所有元素。 此運算子可讓您在數位列中的多個元素上執行更新,而不指定其位置。 當您需要將相同的更新套用至數位中的所有專案時,它特別有用。
語法
db.collection.update(
<query>,
{
$set: {
<arrayField>.$[]: <value>
}
}
)
參數
| 參數 | Description |
|---|---|
<query> |
要更新之文件的選取準則。 |
<arrayField> |
包含要更新之陣列的欄位。 |
<value> |
要為陣列中每個相符項目設定的值。 |
範例
請參考商店集合中的此範例檔。
{
"_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4",
"name": "First Up Consultants | Beverage Shop - Satterfieldmouth",
"location": {
"lat": -89.2384,
"lon": -46.4012
},
"staff": {
"totalStaff": {
"fullTime": 8,
"partTime": 20
}
},
"sales": {
"totalSales": 75670,
"salesByCategory": [
{
"categoryName": "Wine Accessories",
"totalSales": 34440
},
{
"categoryName": "Bitters",
"totalSales": 39496
},
{
"categoryName": "Rum",
"totalSales": 1734
}
]
},
"promotionEvents": [
{
"eventName": "Unbeatable Bargain Bash",
"promotionalDates": {
"startDate": {
"Year": 2024,
"Month": 6,
"Day": 23
},
"endDate": {
"Year": 2024,
"Month": 7,
"Day": 2
}
},
"discounts": [
{
"categoryName": "Whiskey",
"discountPercentage": 7
},
{
"categoryName": "Bitters",
"discountPercentage": 15
},
{
"categoryName": "Brandy",
"discountPercentage": 8
},
{
"categoryName": "Sports Drinks",
"discountPercentage": 22
},
{
"categoryName": "Vodka",
"discountPercentage": 19
}
]
},
{
"eventName": "Steal of a Deal Days",
"promotionalDates": {
"startDate": {
"Year": 2024,
"Month": 9,
"Day": 21
},
"endDate": {
"Year": 2024,
"Month": 9,
"Day": 29
}
},
"discounts": [
{
"categoryName": "Organic Wine",
"discountPercentage": 19
},
{
"categoryName": "White Wine",
"discountPercentage": 20
},
{
"categoryName": "Sparkling Wine",
"discountPercentage": 19
},
{
"categoryName": "Whiskey",
"discountPercentage": 17
},
{
"categoryName": "Vodka",
"discountPercentage": 23
}
]
}
]
}
範例 1:更新折扣百分比
此查詢會更新每個促銷活動內 discounts 陣列中的所有元素。
db.stores.updateOne(
{ _id: "905d1939-e03a-413e-a9c4-221f74055aac" },
{
$inc: {
"promotionEvents.$[].discounts.$[].discountPercentage": 5
}
}
)
範例 2:依類別更新銷售
此查詢會使用 $[] 運算子將所有類別的總銷售額增加 10%。
db.stores.update(
{ _id: "905d1939-e03a-413e-a9c4-221f74055aac" },
{
$mul: {
"sales.salesByCategory.$[].totalSales": 1.10
}
}
)