How to use $push and $pop operators in MongoDB

MongoDB provides the array operators to perform different queries on the arrays. In this answer, we'll discuss $push and $pop operators that are used for updating an array.

We use the following database to perform different logical operators where the database name is educative and has a collection named course.

use educative //selecting our database
db.courses.find({}) //showing all the documents of "courses"
[
{ _id: 10, course_name: 'python', hours: [10,14,20] },
{ _id: 11, course_name: 'C++', hours: [10,15] },
{ _id: 12, course_name: 'java', hours: [10,11,12] }
]
Sample database

Note: There are many other array operators in MongoDB. Click here to learn more.

The $pushoperator

This operator appends the given value into the array. If the specified field doesn't exist in the document, it adds the given field in the array with the specified value.

Syntax

The syntax of $push operator is:

{
$push: {
<field1>: <value1>, ...
}
}

We can also use $push operator with the modifiers $each , $slice , $sort, and $position .

Example

Let's see an example of the $push operator:

//query
db.courses.updateOne({ _id: 11 },{ $push: { hours: 89 } })
//output
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0
}

This query returns modifiedCount and matchedCount with value 1, which means the document has been updated successfully.

After running the above query, our database contains the following documents:

educative> db.courses.find({})
[
{ _id: 10, course_name: 'python', hours: [ 10, 14, 20 ] },
{ _id: 11, course_name: 'C++', hours: [ 10, 15, 89 ] },
{ _id: 12, course_name: 'java', hours: [ 10, 11, 12 ] }
]

The $popoperator

This operator removes the given value from the array. We use -1 to remove the first element and 1 to remove the last element of the array.

Syntax

The syntax of $pop operator is:

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

Example

Let's see an example of $pop operator, where we remove the first element:

//query
db.courses.updateOne( { _id: 10 }, { $pop: { hours: -1 } } )
//output
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0
}

This query returns modifiedCount and matchedCount with value 1, which means the document has been removed successfully.

After running the above query, our database contains the following documents:

educative> db.courses.find({})
[
{ _id: 10, course_name: 'python', hours: [ 14, 20 ] },
{ _id: 11, course_name: 'C++', hours: [ 10, 15 ] },
{ _id: 12, course_name: 'java', hours: [ 10, 11, 12 ] }
]

Note: The $push and $popoperation fail, when specified field is not an array.

Run your queries

You can run all the MongoDB queries mentioned above in the terminal below:

Terminal 1
Terminal
Loading...

Free Resources

HowDev By Educative. Copyright ©2025 Educative, Inc. All rights reserved