$pop

The `$pop` operator is used to remove the first or last element of an array. This operator is useful when you need to manage arrays by removing elements from either end. The `$pop` operator can be used in update operations.

Syntax

{
  $pop: {
    <field>: <value>
  }
}

Parameters

<field>stringrequired

The field that contains the array from which you want to remove an element.

<value>numberrequired

Use 1 to remove the last element, and -1 to remove the first element.

Examples

Sample Data

{
  "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4",
  "name": "First Up Consultants | Beverage Shop - Satterfieldmouth",
  "sales": {
    "salesByCategory": [
      { "categoryName": "Wine Accessories", "totalSales": 34440 },
      { "categoryName": "Bitters", "totalSales": 39496 },
      { "categoryName": "Rum", "totalSales": 1734 }
    ]
  },
  "promotionEvents": [
    { "eventName": "Unbeatable Bargain Bash" },
    { "eventName": "Steal of a Deal Days" }
  ]
}

Remove the last element from an array

Removes the last element from the tag array using $pop with value 1.

Query:

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

Output:

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

Removing the first element from an array

Removes the first element from the promotionEvents array using $pop with value -1.

Query:

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

Output:

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

Related