Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to pop a single value in MongoDB?
To pop a single value in MongoDB, use the $pop operator to remove the first or last element from an array field. The $pop operator takes a value of 1 to remove the last element or -1 to remove the first element.
Syntax
db.collection.updateOne(
{ query },
{ $pop: { "arrayField": 1 } } // Remove last element
);
db.collection.updateOne(
{ query },
{ $pop: { "arrayField": -1 } } // Remove first element
);
Sample Data
Let us first create a collection with documents ?
db.persistChangeDemo.insertOne({
"Name": "Larry",
"CreditScore": [500, 700, 760, 100]
});
{
"acknowledged": true,
"insertedId": ObjectId("5cdfc52cbf3115999ed51203")
}
Following is the query to display all documents from a collection with the help of find() method ?
db.persistChangeDemo.find().pretty();
{
"_id": ObjectId("5cdfc52cbf3115999ed51203"),
"Name": "Larry",
"CreditScore": [
500,
700,
760,
100
]
}
Example: Remove Last Element
Following is the query to pop the last value from the CreditScore array ?
db.persistChangeDemo.updateOne(
{ "Name": "Larry" },
{ $pop: { "CreditScore": 1 } }
);
{
"acknowledged": true,
"matchedCount": 1,
"modifiedCount": 1
}
Verify Result
Let us check the document once again ?
db.persistChangeDemo.find().pretty();
{
"_id": ObjectId("5cdfc52cbf3115999ed51203"),
"Name": "Larry",
"CreditScore": [
500,
700,
760
]
}
Conclusion
Use the $pop operator with value 1 to remove the last element or -1 to remove the first element from an array. This provides precise control over which end of the array to modify.
Advertisements
