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.

Updated on: 2026-03-15T01:29:19+05:30

274 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements