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.
Table of Contents
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.
Let us study them one by one.
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”
};
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);
Hence the document got deleted.
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);
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’
};
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);
This method deletes more than one document; here three documents got deleted from the MongoDB collection “dept”.
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:
There are various types of query selectors we can use based on our requirements. Let see
$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 = [{
Code 2:
db.result.insert(mark)
Code 3:
View the new collection:
db.result.find().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()
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()
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()
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()
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()
No Output because all the three documents belong to the year 2019.
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,
“I think the Software Testing Course is apt for me. Webskitters Academy has offered me the best experience for online training. Every learner can learn more about several concepts. The assignments to write Test cases and Test case Scenarios equipped me to learn to work on real-time projects. I got a job at a reputed firm with the help of the placement cell of this institute. I am extremely happy.”
“After the Software Testing course at Webskitters Academy, I now have the confidence to face testing interviews. I trusted the institute and here they gave me the best of the best. The assignments are great and they helped me to think out of the box and come up with new questions. I am extremely happy and satisfied and also got a job through this institute.”
Kolkata,India
“I am 100% content with the Software Testing course at Webskitters Academy. The professionals explain every question and doubt that aroused in my mind. The entire course is explained the thorough and step-by-step process. It is very professional but the learning method and environment are very friendly.”
Kolkata,India
“I am glad that I took the decision of joining Advanced PHP and MVC (Laravel) online course at Webskitters Academy. I joined the course during the lockdown, to learn programming. However, it is turned out to be more than just a course. It became my passion. The tutors were so good and encouraging. I even got a good placement during the pandemic, just a few days after the completion of the course.”
Kolkata,India
“Learnt PHP Laravel under Swarup Kumar Saha Sir. He is very helpful and excellent trainer. I am done this course online. The training was good I improved my coding skill and also improved my communication skills.”
Kolkata,India
“Learnt PHP With Laravel under Swarup Kumar Saha Sir. He is an excellent trainer. The training was good I improved my coding skills as well as communication skills.”
“I did training on Android App Development using Core Java from here. I guess, I couldn’t have find a better faculty than Swarup Sir. The thing I liked the most is that he is very friendly and always eager to help us on any terms. Apart from teaching us Android in a very great way, he helped us in personality development too, as he always motivated us in a good way. So, I guess these training days were not only for learning but also for finding our own skills and mastering them. Thanks to Webskitters for providing us this opportunity. I would like to learn more from here.”
Kolkata,India
“I had a fantastic experience with this academy. I trained by professionals. I learned Android App Development using Core Java properly and got a job very early in a reputed software company through this academy. Many many thanks to Amit sir, Riyanka ma’am and Debjit sir.”
Kolkata,India
“I have done Android App Development using Core Java training from this academy for one month. They cover most of topic in one month. Trainer (educator) was very supportive and polite.”
Kolkata,India
“Right after completing my Android App Development with KotlinCourse at Webskitters Academy, I landed a job in a reputed firm. This was an incredible experience for me as before that I was looking for a job for almost a year but failed to get any. Thanks to the professional training I took from the experts that helped me start my career instantly.”
Kolkata,India
We are glad to have hired the students from Webskitters Academy! We have to mention that they are trained to be the professionals. From the first day onwards, they have shown their excellence, and it is very impressive. Our team is also happy with their involvement and performance. Looking forward to hire more excellent students from them!
We are happy with the quality of training that the Webskitters Academy students have received. Few of them have been on-board with us recently and they have impressed us. We would recommend our associates to hire freshers from this institute, they make sure that the students are well-trained and prepared for the industry.
We hired the students from Webskitters Academy and to our surprise we found out that they are brilliant in their work! No way we can call them students, they are professionals. They know their work, have the skills and are well-groomed for the profession. Thanks, Webskitters Academy for such a comprehensive training!
“It was for the first time that we hired students from Websitters Academy. We had some doubts regarding freshers, but to our surprise, they are very good in their work. They know exactly how to do a particular job keeping the industry standards in mind. Our organization is happy to have them. Their codes, and development skills are perfect, suitable for the industry. It proves that they have been trained comprehensively. Good work by the faculties of Webskitters Academy. We will definitely recruit more young talents from you.”