Introduction to MongoDB $pop Operator

The MongoDB $pop operator is used to remove the first or last element from an array.

Syntax

The syntax of the $pop operator is as follows:

{ $pop: { <field>: <-1 | 1> } }

Where:

  • <field> represents the array field to operate on.
  • <-1 | 1> is used to specify the position of the element to be removed. -1 means to remove the last element of the array, and 1 means to remove the first element of the array.

Use cases

The $pop operator is commonly used in the following scenarios:

  • Remove the first or last element of an array.
  • When you need to remove an element from an array, using the $pop operator is more convenient.

Examples

Here are two examples of using the $pop operator.

Example 1

Assume there is a users collection that contains the following document:

{
  "_id": 1,
  "username": "user1",
  "scores": [3, 6, 9]
}

To remove the last element from the scores array, you can use the following command:

db.users.updateOne({ _id: 1 }, { $pop: { scores: -1 } })

After executing this command, the value of the scores array is [3, 6].

Example 2

Continuing with the users collection above, if you want to remove the first element from the scores array, you can use the following command:

db.users.updateOne({ _id: 1 }, { $pop: { scores: 1 } })

After executing this command, the value of the scores array is [6, 9].

Conclusion

Through this article, we learned that the $pop operator is used to remove the first or last element from an array and is commonly used in scenarios where array elements need to be removed.