$pop演算子は、配列の最初または最後の要素を削除するために使用されます。 この演算子は、いずれかの端から要素を削除して配列を管理する必要がある場合に便利です。 オペレーターは $pop 、更新操作で使用できます。
構文
{
$pop: {
<field>: <value>
}
}
パラメーター
| パラメーター | Description |
|---|---|
<field> |
要素を削除する配列を含むフィールド。 |
<value> |
最後の要素を削除し1、最初の要素を削除するために使用-1します。 |
例示
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: 配列から最後の要素を削除する
タグ配列から最後の要素を削除するには、値 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 配列から最初の要素を削除するには、$pop演算子を使用して、値 -1 の promotionEvents 配列に対してクエリを実行します。
db.stores.update({
_id: "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5"
}, {
$pop: {
promotionEvents: -1
}
})
このクエリは、次の結果を返します。
[
{
"acknowledged": true,
"insertedId": null,
"matchedCount": "1",
"modifiedCount": "1",
"upsertedCount": 0
}
]