$pullAll(数组更新)

适用对象: MongoDB vCore

$pullAll 运算符用于从数组中删除指定值的所有实例。 当需要在单个操作中删除多个特定元素以清理数组时,此运算符非常有用。

$pull$pullAll 都可用于删除数组中的元素,但其在标识要删除的元素的方式上有所不同。 $pull 从数组中删除匹配特定条件的所有元素,该条件可以是简单的值,也可以是更复杂的查询(如匹配子文档字段)。 另一方面,$pullAll 删除作为完全匹配数组提供的特定值,但不支持条件或查询。 本质上,$pull 更灵活,因为其允许根据各种条件进行条件删除,而 $pullAll 更简单,其只处理一组固定的值。

语法

$pullAll 运算符的语法如下所示:

{
  $pullAll: { <field1>: [ <value1>, <value2>, ... ], ... }
}

参数

说明
<field1> 要删除指定值的字段。
[ <value1>, <value2>, ... ] 要从指定字段中删除的值数组。

示例

让我们通过以下示例 json 来了解用法。

{
  "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
   "name": "Lakeshore Retail | DJ Equipment Stop - Port Cecile",
  "location": {
    "lat": 60.1441,
    "lon": -141.5012
  },
  "staff": {
    "totalStaff": {
      "fullTime": 2,
      "partTime": 0
    }
  },
  "sales": {
    "salesByCategory": [
      {
        "categoryName": "DJ Headphones",
        "totalSales": 35921
      }
    ],
    "fullSales": 3700
  },
  "promotionEvents": [
    {
      "eventName": "Bargain Blitz Days",
      "promotionalDates": {
        "startDate": {
          "Year": 2024,
          "Month": 3,
          "Day": 11
        },
        "endDate": {
          "Year": 2024,
          "Month": 2,
          "Day": 18
        }
      },
      "discounts": [
        {
          "categoryName": "DJ Turntables",
          "discountPercentage": 18
        },
        {
          "categoryName": "DJ Mixers",
          "discountPercentage": 15
        }
      ]
    }
  ],
  "tag": [
    "#ShopLocal",
    "#SeasonalSale",
    "#FreeShipping",
    "#MembershipDeals"
  ]
}

从“tag”数组中删除“#MembershipDeals”和“#SeasonalSale”的折扣。

db.stores.updateMany(
    //filter
    { "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5"},
    {
      $pullAll: {
        "tag": ["#MembershipDeals","#SeasonalSale" ]
      }
    }
)

此查询将返回以下文档。

{
  "acknowledged": true,
  "insertedId": null,
  "matchedCount": 1,
  "modifiedCount": 1,
  "upsertedCount": 0
}