Open In App
Related Articles

MongoDB – $pop Operator

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report
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.
db.contributor.update({name: "Rohit"}, {$pop: { language: -1}})

                    

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.
db.contributor.update({name: "Sumit"}, {$pop: {language: 1}})

                    

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.
db.contributor.update({name: "Sumit"}, 
                      {$pop: {"personal.semesterMarks": -1}})

                    


Last Updated : 10 May, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads