Delete Documents from MongoDB Collection - Webskitters Academy

Delete Documents from MongoDB Collection

After studying this blog, you should be able to perform search operations in MongoDB and also delete documents from Collection. I have implemented the search method from simple key-value pair to multiple JSON objects. The examples will enrich you to write optimized queries.

Later in this blog, I will discuss how to create a Query Selector, understand the different types of Selectors used in MongoDB and how to use these Selectors along with different MongoDB methods to perform enhanced filtering.

Delete operations in MongoDB

So, let’s start with the Delete operation. There are different ways in MongoDB by which we can delete a document from the MongoDB collection.

  • db.collection.deleteOne()
  • db.collection.deleteMany()

Let us study them one by one.

Deleting a single document in MongoDB collection using deleteOne() method

In this example, we have created a variable deptQuery having JSON data for selection query, and the code for the same is as follows:

Code 1

var deptQuery = {

“name”: “it”

};

Deleting a single document in MongoDB

And then, we have used the MongoDB deleteOne() method to delete a single document based on our selection query on the collection “dept”.

Code 2

db.dept.deleteOne(deptQuery);

MongoDB deleteOne()

Hence the document got deleted.

Deleting multiple documents in MongoDB collection using deleteMany() method

This method deletes more than one document in the MongoDB collection.

So, let’s introduce a couple of documents where the filter attribute in common. Based on which deletion will take place:

var deptArr = [

{

name: “eee”,

email: “ec@domain.com”

},

{

name: “eee”,

email: “eee_faculty@domain.com”

}

];

db.dept.insertMany(deptArr);

Deleting multiple documents in MongoDB

Now we have got three documents that have “name”:“eee” which we will delete together.

So now, we have created a variable deptsQuery having JSON data for selection query, and the code for the same is as follows:

Code 1

var deptsQuery = {

‘name’: ‘eee’

};

Deleting multiple documents in MongoDB

And then, we have used the MongoDB deleteMany() method to delete multiple documents based on our selection query in the MongoDB collection “dept”.

Code 2

db.dept.deleteMany(deptsQuery);

MongoDB deleteMany()

This method deletes more than one document; here three documents got deleted from the MongoDB collection “dept”.

MongoDB delete operation using Query Selectors

Whenever we query a MongoDB database, it fetches some data stored in the Mongo documents from various MongoDB collections. There are different requirements for data throughout the application. Sometimes, we need to use small data for a specific action in the application, or we need to update this data based on some criteria. And even sometimes, we need to delete some old documents based on some condition. In these situations, we need something, which will help us to work on only those documents, which are needed for CRUD or Data Manipulation operations.

In this regard, query selectors are helpful for the following:

  • Fetch the MongoDB documents from the collections based on some conditions
  • Modify the multiple documents based on some conditions
  • Delete the multiple documents based on some conditions

There are various types of query selectors we can use based on our requirements. Let see

  • Comparison Selectors:

$eq     This selector matches the documents that have values to the specified value

$gt     This selector matches the documents that have values greater than the specified value

$gte   This selector matches the documents that have values greater than or equal to the specified value

$in      This selector matches the documents that have any of the values specified in an array

$lt      This selector matches the documents that have values less than the specified value

$lte    This selector matches the documents that have values less than or equal to the specified value

$ne     This selector matches the documents that have values not equal to the specified value

$nin    This selector matches the documents that have none of the values specified in an array

To illustrate these selectors, we will create one new Collection: “result”. To create an array-

Code 1:

var mark = [{

MongoDB delete operation using Query Selectors

Code 2:

db.result.insert(mark)

MongoDB delete operation using Query Selectors

Code 3:

View the new collection:

db.result.find().pretty()

MongoDB delete operation using Query Selectors

Examples of comparison selectors

Example 1 – Sgt Comparison Selector

In our example, we have used the “$gt” comparison selector in our collection “result” in the field “subject.lab” to find all the documents that have their “subject.lab” greater than 26.

The code and the selector details for the same are shown in the following screenshot

Code:

db.result.find({

‘subject.lab’:{$gt:26}

}).pretty()

Examples of comparison selectors

Example 1 – Sgt Comparison Selector

In our example, we have used the “$gt” comparison selector in our collection “result” in the field “subject.lab” to find all the documents that have their “subject.lab” greater than 26.

The code and the selector details for the same are shown in the following screenshot

Code:

db.result.find({

‘subject.lab’:{$gt:26}

}).pretty()

$lte comparison selector

Example 3 – $eq comparison selector

In our example, we have used the “$eq” comparison selector in our collection ” result ” in the field “name ” to find all the documents that have their “name” is exactly “Raj” from the list of objects in the JSON Array.

Code:

db.result.find({

‘name’:{$eq:’Raj’}

}).pretty()

$eq comparison selector

  • Logical Selectors

These types of selectors are helpful to perform the CRUD operations based on the logical conditions. The list of logical selectors:

$and   This selector performs the logical AND operation on different expressions and joins both the queries to deliver the combined result by returning all the documents based on the Join

$not   This selector performs the logical NOT operation and returns the documents that do not match the expression

$or     This selector performs the logical OR operation on different expressions and joins both the queries to deliver the combined result by returning all the documents based on the Join

Example 1 – $and logical selector

In our example, we have used the “$and” logical selector in our collection “result” in the fields “name” and “year” to find all the documents that have the “name” greater than or equal to “Raj” and “year” equal to 2019. The code and the selector details for the same are shown in the following screenshot:

Code:

db.result.find({

$and:[{

name: {$eq: “Raj”},

year: {$eq: “2019”}

}]

}).pretty()

Logical Selectors

Example 2 – $not logical selector

In our example, we have used the “$not” logical selector in our collection. “result” in the field “year” to find all the documents that have the “year” not equal to 2019.

Code:

db.result.find({

year: {

$not:{$eq: “2019”}

}

}).pretty()

$not logical selector

No Output because all the three documents belong to the year 2019.

 Conclusion

In this blog, we studied the MongoDB Delete operations and learned different parameters based on which delete can be performed.

We also learned about the MongoDB array containing multiple JSON objects. Using that we learn about the various Query Selectors which will be used to perform various MongoDB queries to achieve delete or search operations. Search and delete operation involving multiple key-value pairs we saw through query selectors.

Following the queries and the screenshot that I presented in the blog will surely help all of you in learning MongoDB for applying it in real-life applications. For more information and updated knowledge, develop your skills by getting trained on the full-stack development. Join the high-end and popular full-stack development courses, MERN Stack and MEAN Stack, and learn the details from the industry experts.

In the next blog, we will cover MongoDB Projection Operators based on which our search criteria will be more refined.

Coming Soon: Introduction to Projection Operators in MongoDB

Also Read, 

Swarup Kr Saha

Swarup Kr Saha is a Senior Technical Analyst cum Corporate Trainer. He is seasoned and successful in creating fresher’s training programs for the IT aspirants and helping them excel in their careers. An enthusiast in IoT, he has more than 10 years of experience. He believes in a continuous learning procedure and is committed to providing Quality Training in the areas of ABCD (Application Development, Big Data, Cloud and Database). Using his exemplary skills, he also develops Full-Stack Web and Mobile (Android & iOS) App connecting IoT with REST-API based solutions.

What Students are Saying

Students Get Placed in

What Our Clients Are Saying

Call Request Form