DEV Community

Cover image for Delete Documents, Drop Collection in MongoDB
KAWSAR KABIR
KAWSAR KABIR

Posted on

Delete Documents, Drop Collection in MongoDB

To delete documents in MongoDB, you can use the deleteOne() or deleteMany() methods. These methods allow you to remove one or multiple documents, respectively.

Here’s an example of using the deleteOne() method to remove a single document:

db.collection.deleteOne({ _id: ObjectId("your_document_id_here") });
Enter fullscreen mode Exit fullscreen mode

If you want to delete all documents, you can use the deleteMany() method:

db.collection.deleteMany({});
Enter fullscreen mode Exit fullscreen mode

Additionally, you can delete all documents that match a specific condition:

db.collection.deleteMany({ your_query_here });
Enter fullscreen mode Exit fullscreen mode

To delete an entire collection, use the drop() method:

db.collection.drop();
Enter fullscreen mode Exit fullscreen mode

This method removes the collection entirely, so it should be used with caution, as all data will be permanently deleted. Make sure to back up your data before performing this operation.

Top comments (0)