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
Deleting all records of a collection in MongoDB Shell?
To delete all records of a collection in MongoDB shell, use the remove() method with an empty filter document. This operation removes all documents from the collection but keeps the collection structure intact.
Syntax
db.collectionName.remove({});
Create Sample Data
Let us create a collection with sample documents ?
db.deleteAllRecordsDemo.insertMany([
{"StudentName": "John"},
{"StudentName": "Carol", "StudentAge": 21},
{"StudentName": "Mike", "StudentAge": 23, "Hobby": ["Learning", "Photography"]}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5c8f6ca32f684a30fbdfd596"),
ObjectId("5c8f6cb22f684a30fbdfd597"),
ObjectId("5c8f6cde2f684a30fbdfd598")
]
}
Display Current Documents
db.deleteAllRecordsDemo.find().pretty();
{
"_id": ObjectId("5c8f6ca32f684a30fbdfd596"),
"StudentName": "John"
}
{
"_id": ObjectId("5c8f6cb22f684a30fbdfd597"),
"StudentName": "Carol",
"StudentAge": 21
}
{
"_id": ObjectId("5c8f6cde2f684a30fbdfd598"),
"StudentName": "Mike",
"StudentAge": 23,
"Hobby": [
"Learning",
"Photography"
]
}
Delete All Records
db.deleteAllRecordsDemo.remove({});
WriteResult({ "nRemoved": 3 })
Verify Result
Check if all documents have been deleted ?
db.deleteAllRecordsDemo.find();
The collection is now empty as all documents have been successfully removed.
Conclusion
The remove({}) method with an empty filter deletes all documents from a MongoDB collection while preserving the collection structure. Use deleteMany({}) for the same operation in modern MongoDB versions.
Advertisements
