How to remove document on the basis of _id in MongoDB?

To remove a document based on its _id in MongoDB, use the remove() method with the ObjectId as the matching criteria. Each document has a unique _id field that serves as the primary key.

Syntax

db.collectionName.remove({"_id": ObjectId("yourObjectId")});

Sample Data

Let us first create a collection with sample documents ?

db.removeDocumentOnBasisOfId.insertMany([
    {"UserName": "Larry", "UserAge": 23, "UserCountryName": "US"},
    {"UserName": "Sam", "UserAge": 21, "UserCountryName": "UK"},
    {"UserName": "Chris", "UserAge": 24, "UserCountryName": "US"},
    {"UserName": "Robert", "UserAge": 26, "UserCountryName": "UK"},
    {"UserName": "David", "UserAge": 28, "UserCountryName": "AUS"}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5c986f9f330fd0aa0d2fe4a3"),
        ObjectId("5c986fb4330fd0aa0d2fe4a4"),
        ObjectId("5c986fc0330fd0aa0d2fe4a5"),
        ObjectId("5c986fcf330fd0aa0d2fe4a6"),
        ObjectId("5c986fed330fd0aa0d2fe4a7")
    ]
}

Display All Documents

db.removeDocumentOnBasisOfId.find().pretty();
{
    "_id": ObjectId("5c986f9f330fd0aa0d2fe4a3"),
    "UserName": "Larry",
    "UserAge": 23,
    "UserCountryName": "US"
}
{
    "_id": ObjectId("5c986fb4330fd0aa0d2fe4a4"),
    "UserName": "Sam",
    "UserAge": 21,
    "UserCountryName": "UK"
}
{
    "_id": ObjectId("5c986fc0330fd0aa0d2fe4a5"),
    "UserName": "Chris",
    "UserAge": 24,
    "UserCountryName": "US"
}
{
    "_id": ObjectId("5c986fcf330fd0aa0d2fe4a6"),
    "UserName": "Robert",
    "UserAge": 26,
    "UserCountryName": "UK"
}
{
    "_id": ObjectId("5c986fed330fd0aa0d2fe4a7"),
    "UserName": "David",
    "UserAge": 28,
    "UserCountryName": "AUS"
}

Example: Remove Document by _id

Remove Chris's document using its _id ?

db.removeDocumentOnBasisOfId.remove({"_id": ObjectId("5c986fc0330fd0aa0d2fe4a5")});
WriteResult({ "nRemoved": 1 })

Verify Result

Check if the document has been removed successfully ?

db.removeDocumentOnBasisOfId.find().pretty();
{
    "_id": ObjectId("5c986f9f330fd0aa0d2fe4a3"),
    "UserName": "Larry",
    "UserAge": 23,
    "UserCountryName": "US"
}
{
    "_id": ObjectId("5c986fb4330fd0aa0d2fe4a4"),
    "UserName": "Sam",
    "UserAge": 21,
    "UserCountryName": "UK"
}
{
    "_id": ObjectId("5c986fcf330fd0aa0d2fe4a6"),
    "UserName": "Robert",
    "UserAge": 26,
    "UserCountryName": "UK"
}
{
    "_id": ObjectId("5c986fed330fd0aa0d2fe4a7"),
    "UserName": "David",
    "UserAge": 28,
    "UserCountryName": "AUS"
}

Conclusion

Use remove({"_id": ObjectId("id")}) to delete a specific document by its unique identifier. The WriteResult confirms successful removal with nRemoved: 1.

Updated on: 2026-03-15T00:24:40+05:30

310 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements