MongoDB Array Update Operator - $pop
MongoDB $pop
In MongoDB, the $pop operator removes the first or last element of an array. The value -1 is used with $pop to remove the first element of an array and 1 for the last element.
Syntax:
db.collection.update( {field: value }, { $pop: { field: [1 | -1] } } );
Parameters:
Name | Description |
---|---|
field | name of the column or field to the document.. |
Sample collection "student"
{
"_id" : 1,
"sem" : 1,
"achieve" : [
70,
87,
90,
90,
65,
81
]
}
Example of MongoDB $pop to remove the last element
If we want to remove the last element from the array field achieve for any instance of 70 in this array, the following mongodb command can be used -
> db.student.update( {achieve: 70 }, { $pop: { achieve : 1 } } );
To see the newly updated document -
> db.student.find().pretty();
Output of the command:
{ "_id" : 1, "achieve" : [ 70, 87, 90, 90, 65 ], "sem" : 1 }
Example of MongoDB $pop to remove first element
If we want to remove the first element from the array field achieve for any instance of 70 in this array, the following mongodb command can be used -
> db.student.update( {achieve: 70 }, { $pop: { achieve : -1 } } );
To see the newly updated document -
> db.student.find().pretty();
Output of the command
{ "_id" : 1, "achieve" : [ 87, 90, 90, 65, 81 ], "sem" : 1 }
Previous:
Array Update Operators $addToSet
Next:
$pull
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/mongodb/mongodb-array-update-operator-$pop.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics