DocumentDB の $[] 演算子は、指定した条件に一致する配列内のすべての要素を更新するために使用されます。 この演算子を使用すると、配列内の複数の要素の位置を指定せずに更新を実行できます。 これは、配列内のすべての項目に同じ更新を適用する必要がある場合に特に便利です。
構文
db.collection.update(
<query>,
{
$set: {
<arrayField>.$[]: <value>
}
}
)
パラメーター
| パラメーター | Description |
|---|---|
<query> |
更新するドキュメントの選択基準。 |
<arrayField> |
更新する配列を含むフィールド。 |
<value> |
配列内の一致する要素ごとに設定する値。 |
例示
stores コレクションのこのサンプル ドキュメントについて考えてみましょう。
{
"_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
}
}
)