Open In App

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.

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}})


Article Tags :