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 databasedb.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] }]
Note: There are many other array operators in MongoDB. Click here to learn more.
$push
operatorThis 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.
The syntax of $push
operator is:
{$push: {<field1>: <value1>, ...}}
We can also use $push
operator with the modifiers $each
, $slice
, $sort
, and $position
.
Let's see an example of the $push
operator:
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 ] }]
$pop
operatorThis 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.
The syntax of $pop
operator is:
{$pop: {<field>: <-1 | 1>, ...}}
Let's see an example of $pop
operator, where we remove the first element:
//querydb.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$pop
operation fail, when specified field is not an array.
You can run all the MongoDB queries mentioned above in the terminal below:
Free Resources