$pop運算子是用來移除陣列的第一個或最後一個專案。 當您需要從任一端移除元素來管理數位時,這個運算子很有用。
$pop運算子可用於更新作業。
語法
{
$pop: {
<field>: <value>
}
}
參數
| 參數 | Description |
|---|---|
<field> |
包含您要從中移除元素之陣列的欄位。 |
<value> |
使用 1 移除最後一個專案,以及 -1 移除第一個專案。 |
範例
請參考商店集合中的此範例檔。
{
"_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:從陣列中移除最後一個元素
若要從標籤陣列中移除最後一個元素,請在值為 1 的標籤欄位上使用 $pop 運算子執行查詢。
db.stores.update({
_id: "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5"
}, {
$pop: {
tag: 1
}
})
此查詢會傳回下列結果。
[
{
"acknowledged": true,
"insertedId": null,
"matchedCount": "1",
"modifiedCount": "1",
"upsertedCount": 0
}
]
範例 2:從陣列中移除第一個元素
若要從 promotionEvents 陣列中移除第一個元素,請在值為 -1 的 promotionEvents 陣列上使用 $pop 運算子執行查詢。
db.stores.update({
_id: "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5"
}, {
$pop: {
promotionEvents: -1
}
})
此查詢會傳回下列結果。
[
{
"acknowledged": true,
"insertedId": null,
"matchedCount": "1",
"modifiedCount": "1",
"upsertedCount": 0
}
]