$pop(数组更新)

MongoDB 中的 $pop 运算符用于删除数组的第一个或最后一个元素。 需要通过删除任一端的元素以管理数组时,此运算符非常有用。 $pop 运算符可用于更新操作。

语法

{ $pop: { <field>: <value> } }
  • <field>:包含要从中删除元素的数组的字段。
  • <value>:使用 1 删除最后一个元素,使用 -1 删除第一个元素。

参数

说明
<field> 包含要从中删除元素的数组的字段。
<value> 使用 1 删除最后一个元素,使用 -1 删除第一个元素。

示例

让我们通过以下示例 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"
  ]
}

示例 1:删除 tag 数组中的最后一个标签

db.stores.update(
  { "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5" },
  { $pop: { "tag": 1 } }
)

此查询将返回以下文档。 删除数组中的最后一个元素。

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

示例 2:删除 promotionEvents 数组中的最后一个折扣

db.stores.update(
  { "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5" },
  { $pop: { "promotionEvents": -1 } }
)

此查询将返回以下文档。 删除数组中的第一个元素。

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