適用対象:
MongoDB 仮想コア
$
位置指定演算子は、配列内の要素の位置を明示的に指定せずに、更新する配列内の要素を識別します。
$
演算子は、クエリ条件に一致する最初の要素のプレースホルダーとして機能し、配列フィールドはクエリ ドキュメントの一部として表示される必要があります。
構文
$
位置指定演算子の構文は次のとおりです。
db.collection.updateOne(
{ <array>: <value> },
{ <update operator>: { "<array>.$": <value> } }
)
パラメーター
説明 | |
---|---|
array |
更新する要素を含む配列フィールド。 クエリ条件の一部である必要があります。 |
value |
クエリ条件の配列要素と一致するために使用される値。 |
update operator |
適用する更新演算子 (たとえば、 $set 、 $inc 、 $unset )。 |
例
stores
データセットのサンプル JSON の使用方法を理解しましょう。
{
"_id": "905d1939-e03a-413e-a9c4-221f74055aac",
"name": "Trey Research | Home Office Depot - Lake Freeda",
"location": { "lat": -48.9752, "lon": -141.6816 },
"staff": { "employeeCount": { "fullTime": 12, "partTime": 19 } },
"sales": {
"salesByCategory": [ { "categoryName": "Desk Lamps", "totalSales": 37978 } ],
"revenue": 37978
},
"promotionEvents": [
{
"eventName": "Crazy Deal Days",
"promotionalDates": {
"startDate": { "Year": 2023, "Month": 9, "Day": 27 },
"endDate": { "Year": 2023, "Month": 10, "Day": 4 }
},
"discounts": [
{ "categoryName": "Desks", "discountPercentage": 22 },
{ "categoryName": "Filing Cabinets", "discountPercentage": 23 }
]
},
{
"eventName": "Incredible Markdown Mania",
"promotionalDates": {
"startDate": { "Year": 2023, "Month": 12, "Day": 26 },
"endDate": { "Year": 2024, "Month": 1, "Day": 2 }
},
"discounts": [
{ "categoryName": "Monitor Stands", "discountPercentage": 20 },
{ "categoryName": "Desks", "discountPercentage": 24 }
]
}
]
}
例 1: 特定のカテゴリの割引率を更新する
この例では、最初に一致するプロモーション イベントの "Desks" カテゴリの割引率を更新します。
db.stores.updateOne(
{
"_id": "905d1939-e03a-413e-a9c4-221f74055aac",
"promotionEvents.discounts.categoryName": "Desks"
},
{
$set: { "promotionEvents.$.discounts.$[elem].discountPercentage": 25 }
},
{
arrayFilters: [{ "elem.categoryName": "Desks" }]
}
)
例 2: 売上カテゴリの合計を更新する
この例では、 $ (positional operator)
を使用して、特定のカテゴリの売上合計を更新します。
db.stores.updateOne(
{
"_id": "905d1939-e03a-413e-a9c4-221f74055aac",
"sales.salesByCategory.categoryName": "Desk Lamps"
},
{
$inc: { "sales.salesByCategory.$.totalSales": 1000 }
}
)
このクエリでは、"Desk ランプ" カテゴリの売上合計が 1000 増加し、37978 から 38978 に更新されます。
{
"_id": "905d1939-e03a-413e-a9c4-221f74055aac",
"sales": {
"salesByCategory": [ { "categoryName": "Desk Lamps", "totalSales": 38978 } ],
"revenue": 37978
}
}
関連コンテンツ
- MongoDB から Azure Cosmos DB for MongoDB (仮想コア) に移行するためのオプションを確認します。
- MongoDB との機能の互換性について詳細を確認する。