MongoDB – $pop Operator

MongoDB provides different types of array update operators to update the values of the array fields in the documents and $pop operator is one of them. This operator is used to remove the first or the last item from the array.

Syntax:

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

Here, <field> can specify with dot notation in embedded/nested documents or an array.

  • If you pass -1 value in $pop operator, then it will remove the first item from the array.
  • If you pass 1 value in $pop operator, then it will remove the last item from the array.
  • If the <field> is not an array, then this operator will fail.
  • If $pop operator will remove the last item from the specified field, then the field holds an empty array.
  • You can use this operator with methods like update(), findAndModify(), etc., according to your requirement.

In the following examples, we are working with:

Database: GeeksforGeeks
Collection: contributor
Document: two documents that contain the details of the contributor in the form of field-value pairs.



Removing first item from the array:

In this example, we are removing the first element of the language field in the document that matches the specified condition, i.e., name: “Rohit”, by setting the value of $pop operator to -1.

filter_none

edit
close

play_arrow

link
brightness_4
code

db.contributor.update({name: "Rohit"}, {$pop: { language: -1}})

chevron_right


Removing last item from the array:

In this example, we are removing the last element of the language field in the document that matches the specified condition, i.e., name: “Sumit”, by setting the value of $pop operator to 1.

filter_none

edit
close

play_arrow

link
brightness_4
code

db.contributor.update({name: "Sumit"}, {$pop: {language: 1}})

chevron_right


Removing first item from the embedded/nested document:

In this example, we are removing the last element of the personal.semesterMarks field in the nested document by setting the value of $pop operator to -1.

filter_none

edit
close

play_arrow

link
brightness_4
code

db.contributor.update({name: "Sumit"}, 
                      {$pop: {"personal.semesterMarks": -1}})

chevron_right





My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.