MongoDB

MongoDB Delete Documents: deleteOne and deleteMany

Learn how to remove documents in MongoDB safely with deleteOne and deleteMany. See practical mongosh examples and avoid wiping a whole collection by mistake.

Serhat ALPASLAN1 min read

MongoDB Data Deletion

To delete data in MongoDB, follow these steps:

  1. Connect: Open the mongodb command-line client to connect to the relevant MongoDB database, or connect to an application that establishes a MongoDB connection.
  2. Select a collection: Select the collection from which you want to delete data.
  3. Identify the data you want to delete: To identify the data you want to delete, you can filter by a specific field of the data. For example, if you want to delete all students in the “students” collection, you can use a filter like the following
db.students.deleteMany({})
  1. Delete: The deleteOne() method deletes a single document, while the deleteMany() method deletes multiple documents. For example, the following code deletes all students in the “students” collection.
db.students.deleteMany({})
  1. Confirm: To confirm the deletion, you can use the deletedCount property. This property shows the number of deleted documents. For example, the following code checks whether the data in the “students” collection has been deleted:
var result = db.students.deleteMany({});
print("Deleted Count: " + result.deletedCount);

Please note that deleted data cannot be recovered. Use with caution.

 

MongoDB Official Documentation

Share it if it helped

Write a comment