演算子は $pull 、指定した値または条件に一致する値のすべてのインスタンスを配列から削除するために使用されます。 これは、ドキュメント内の配列データをクリーンアップまたは変更する必要がある場合に便利です。
構文
{
$pull: { <field>: <value|condition> }
}
パラメーター
| パラメーター | Description |
|---|---|
<field> |
1 つ以上の値を削除するフィールド。 |
<value|condition> |
配列から削除する値または条件。 |
例示
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: 配列から特定のタグを削除する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 配列からすべてのイベントを削除する
endDate 年が 2024 年で、endDate 月が 3 月より前である promotionEvents 配列からすべての要素を削除するには、指定した日付値を持つ 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
}
]