$位置運算子會識別陣列中要更新的專案,而不明確指定陣列中專案的位置。 運算子 $ 會做為符合查詢條件之第一個專案的佔位元,而且陣列欄位必須顯示為查詢檔的一部分。
語法
db.collection.updateOne(
{ <array>: <value> },
{ <update operator>: { "<array>.$": <value> } }
)
參數
| 參數 | Description |
|---|---|
array |
包含要更新之項目的陣列欄位。 必須是查詢條件的一部分。 |
value |
值,用來比對查詢條件中的陣列專案。 |
update operator |
要套用的更新運算子(例如、$set、 $inc$unset。 |
範例
請參考商店集合中的此範例檔。
{
"_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:投影陣列的第一個元素,符合條件
此查詢會傳回陣列內 salesByCategory 的第一個元素,適用於 DJ 大於 35000 的 totalSales 設備。
db.stores.find({
"sales.salesByCategory": {
$elemMatch: {
categoryName: {
$regex: "^DJ"
}
}
},
"sales.salesByCategory.totalSales": {
$gt: 35000
}
}, {
"sales.salesByCategory.$": 1
}).limit(2)
此查詢傳回的前兩個結果是:
[
{
"_id": "d3c9df51-41bd-4b4e-a26b-b038d9cf8b45",
"sales": {
"salesByCategory": [
{
"categoryName": "DJ Speakers",
"totalSales": 36972
}
]
}
},
{
"_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
"sales": {
"salesByCategory": [
{
"categoryName": "DJ Headphones",
"totalSales": 35911
}
]
}
}
]
範例 2:更新特定類別的折扣百分比
此查詢會更新第一個相符促銷事件中「Desks」類別的折扣百分比。
db.stores.updateOne(
{
_id: "905d1939-e03a-413e-a9c4-221f74055aac",
"promotionEvents.discounts.categoryName": "Desks"
},
{
$set: { "promotionEvents.$.discounts.$[elem].discountPercentage": 25 }
},
{
arrayFilters: [{ "elem.categoryName": "Desks" }]
}
)
範例 3:更新銷售類別總計
此查詢會使用 更新 $ (positional operator)特定類別的總銷售額。
db.stores.updateOne(
{
_id: "905d1939-e03a-413e-a9c4-221f74055aac",
"sales.salesByCategory.categoryName": "Desk Lamps"
},
{
$inc: { "sales.salesByCategory.$.totalSales": 1000 }
}
)