$pull運算子是用來從陣列中移除符合條件之指定值或值的所有實例。 當您需要清除或修改檔中的陣列數據時,這會很有用。
語法
{
$pull: { <field>: <value|condition> }
}
參數
| 參數 | Description |
|---|---|
<field> |
要從中移除一或多個值的欄位。 |
<value|condition> |
要從陣列中移除的值或條件。 |
範例
請參考商店集合中的此範例檔。
{
"_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:從 tag 陣列移除特定標記
若要從標籤陣列欄位中移除值 “#SeasonalSale”,請在標籤欄位上使用 $pull 運算子執行查詢。
db.stores.update({
_id: "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5"
}, {
$pull: {
tag: "#SeasonalSale"
}
})
此查詢會傳回下列結果。
[
{
"acknowledged": true,
"insertedId": null,
"matchedCount": "1",
"modifiedCount": "1",
"upsertedCount": 0
}
]
範例 2:從結束於 promotionEvents 特定日期的陣列中移除所有事件
若要從 promotionEvents 陣列中移除 endDate 年份為 2024 且 endDate 月份早於 3 月的所有元素,請在 promotionEvents 欄位上使用 $pull 運算子執行查詢,並具有指定的日期值。
db.stores.update({
_id: "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5"
}, {
$pull: {
promotionEvents: {
"promotionalDates.endDate.Year": 2024,
"promotionalDates.endDate.Month": {
$lt: 3
}
}
}
}
)
此查詢會傳回下列結果。
[
{
"acknowledged": true,
"insertedId": null,
"matchedCount": "1",
"modifiedCount": "1",
"upsertedCount": 0
}
]