How to delete single and multiple documents in MongoDB
MongoDB is a document-oriented open source database type of NoSQL database.
The basic operations of any database include CRUD. CRUD operations stand for creating, reading, updating, and deleting documents. A thorough explanation of the deletion methods in MongoDB is as follows:
Deletion methods
Delete operation removes or deletes the documents from the collection that matches the specified query conditions. There are two methods to delete documents in MongoDB:
db.collection.deleteOne()db.collection.deleteMany()
We'll use the following database to perform delete operations where the database name is educative and has a collection named courses".
use educative //selecting our databasedb.courses.find({}) //showing all documents in courses[{ _id: 10, course_name: 'python', hours: 10 },{ _id: 11, course_name: 'C++', hours: 15 },{ _id: 12, course_name: 'java', hours: 12 }]
The deleteOne() method
This method deletes or removes the single document from the collection that matches the given query clause. It deletes only one document even if conditions match more than one document.
Syntax
The syntax of deleteOne() query is:
db.collection.deleteOne({<field>:<value>})
Here, field is a unique identifier to store data values.
Example
Here's an example of deleteOne() query:
//querydb.courses.deleteOne({'_id': 11})//output{ acknowledged: true, deletedCount: 1 }
After running the deleteOne() query, our database contains the following documents:
educative> db.courses.find({})[{ _id: 10, course_name: 'python', hours: 10 },{ _id: 12, course_name: 'java', hours: 12 }]
Note: Learn about inserting documents in MongoDB here.
The deleteMany() method
This method deletes or removes the multiple documents from the collection that matches the given query clause. If we want to delete all the documents, we use the filter parameter deleteMany()without query condition.
Syntax
The syntax of deleteMany() query is:
db.collection.deleteMany({<field>:<value>})
Example
Here's an example of deleteMany() query, where we delete all the _id values that are greater or equal to 11:
//querydb.courses.deleteMany({"_id": {$gte: 11}})//output{ acknowledged: true, deletedCount: 2 }
After running the deleteMany() query, our database contains the following documents:
db.courses.find()[{ _id: 10, course_name: 'python', hours: 10 }]
If we want to delete all the documents, we run the following query:
//querydb.courses.deleteMany({})//output{ acknowledged: true, deletedCount: 3 }
Run the queries
We can run all the previously mentioned MongoDB queries in the terminal below:
Free Resources