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 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
-
$neoperator means "not equal to" and excludes matching documents from deletion. -
deleteMany()is the modern alternative toremove(). - 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.
Advertisements
