How to remove all documents from a collection except a single document in MongoDB?

To remove all documents from a collection except a single document in MongoDB, use deleteMany() or remove() with the $ne operator to exclude documents that match a specific condition.

Syntax

db.collection.deleteMany({ field: { $ne: value } });
// OR
db.collection.remove({ field: { $ne: value } });

Create Sample Data

db.removeAllDocumentsExceptOneDemo.insertMany([
    {"StudentName": "Larry", "StudentAge": 21},
    {"StudentName": "Mike", "StudentAge": 21, "StudentCountryName": "US"},
    {"StudentName": "Chris", "StudentAge": 24, "StudentCountryName": "AUS"}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5c9c9de42d66697741252478"),
        ObjectId("5c9c9dea2d66697741252479"),
        ObjectId("5c9c9def2d6669774125247a")
    ]
}

Display All Documents

db.removeAllDocumentsExceptOneDemo.find().pretty();
{
    "_id": ObjectId("5c9c9de42d66697741252478"),
    "StudentName": "Larry",
    "StudentAge": 21
}
{
    "_id": ObjectId("5c9c9dea2d66697741252479"),
    "StudentName": "Mike",
    "StudentAge": 21,
    "StudentCountryName": "US"
}
{
    "_id": ObjectId("5c9c9def2d6669774125247a"),
    "StudentName": "Chris",
    "StudentAge": 24,
    "StudentCountryName": "AUS"
}

Remove All Except One Document

Remove all documents except those with StudentAge 24 ?

db.removeAllDocumentsExceptOneDemo.remove({ StudentAge: { $ne: 24 } });
WriteResult({ "nRemoved": 2 })

Verify Result

db.removeAllDocumentsExceptOneDemo.find().pretty();
{
    "_id": ObjectId("5c9c9def2d6669774125247a"),
    "StudentName": "Chris",
    "StudentAge": 24,
    "StudentCountryName": "AUS"
}

Key Points

  • $ne operator means "not equal to" and excludes matching documents from deletion.
  • deleteMany() is the modern alternative to remove().
  • Use specific field values to preserve the exact document you want to keep.

Conclusion

Use remove() or deleteMany() with the $ne operator to exclude specific documents from deletion. This effectively removes all documents except those that match your preservation criteria.

Updated on: 2026-03-15T00:34:30+05:30

841 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements