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:

  1. db.collection.deleteOne()

  2. 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 database
db.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 }
]
Sample database

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:

//query
db.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:

//query
db.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:

//query
db.courses.deleteMany({})
//output
{ acknowledged: true, deletedCount: 3 }

Run the queries

We can run all the previously mentioned MongoDB queries in the terminal below:

Terminal 1
Terminal
Loading...

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved