To delete all records of a collection in MongoDB shell, use the remove() method. The syntax is as follows −
db.yourCollectionName.remove({});To understand the syntax, let us create a collection with document. The query to create a collection with document is as follows −
> db.deleteAllRecordsDemo.insertOne({"StudentName":"John"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8f6ca32f684a30fbdfd596")
}
> db.deleteAllRecordsDemo.insertOne({"StudentName":"Carol","StudentAge":21});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8f6cb22f684a30fbdfd597")
}
> db.deleteAllRecordsDemo.insertOne({"StudentName":"Mike","StudentAge":23,"Hobby":["Learning","Photography"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8f6cde2f684a30fbdfd598")
}Display all documents from a collection with the help of find() method. The query is as follows −
> db.deleteAllRecordsDemo.find().pretty();
The following is the output −
{ "_id" : ObjectId("5c8f6ca32f684a30fbdfd596"), "StudentName" : "John" }
{
"_id" : ObjectId("5c8f6cb22f684a30fbdfd597"),
"StudentName" : "Carol",
"StudentAge" : 21
}
{
"_id" : ObjectId("5c8f6cde2f684a30fbdfd598"),
"StudentName" : "Mike",
"StudentAge" : 23,
"Hobby" : [
"Learning",
"Photography"
]
}Here is the query to delete all records of a collection in MongoDB:
> db.deleteAllRecordsDemo.remove({});
WriteResult({ "nRemoved" : 3 })Look at the above query, we have deleted all records from a collection. If you try to get records from the above collection, you will get nothing.
The query is as follows −
> db.deleteAllRecordsDemo.find().pretty();
The following is the output −
>