$pop

Definition

  • $pop
  • The $pop operator removes the first or last element of anarray. Pass $pop a value of -1 to remove the firstelement of an array and 1 to remove the last element in anarray.

The $pop operator has the form:

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

To specify a <field> in an embedded document or in an array, usedot notation.

Behavior

The $pop operation fails if the <field> is not an array.

If the $pop operator removes the last item in the<field>, the <field> will then hold an empty array.

Examples

Remove the First Item of an Array

Given the following document in a collection students:

  1. { _id: 1, scores: [ 8, 9, 10 ] }

The following example removes the first element (8) in thescores array:

  1. db.students.update( { _id: 1 }, { $pop: { scores: -1 } } )

After the operation, the updated document has the first item 8removed from its scores array:

  1. { _id: 1, scores: [ 9, 10 ] }

Remove the Last Item of an Array

Given the following document in a collection students:

  1. { _id: 1, scores: [ 9, 10 ] }

The following example removes the last element (10) in thescores array by specifying 1 in the $pop expression:

  1. db.students.update( { _id: 1 }, { $pop: { scores: 1 } } )

After the operation, the updated document has the last item 10removed from its scores array:

  1. { _id: 1, scores: [ 9 ] }

See also

db.collection.update(),db.collection.findAndModify()