Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Implement multiple conditions in MongoDB?
Let us first create a collection with documents −
> db.multipleConditionDemo.insertOne({"_id":1,"Name":"John"});
{ "acknowledged" : true, "insertedId" : 1 }
> db.multipleConditionDemo.insertOne({"_id":2,"Name":"Carol"});
{ "acknowledged" : true, "insertedId" : 2 }
> db.multipleConditionDemo.insertOne({"_id":3,"Name":"Sam"});
{ "acknowledged" : true, "insertedId" : 3 }
> db.multipleConditionDemo.insertOne({"_id":4,"Name":"David"});
{ "acknowledged" : true, "insertedId" : 4 }
Following is the query to display all documents from a collection with the help of find() method −
> db.multipleConditionDemo.find().pretty();
This will produce the following output −
{ "_id" : 1, "Name" : "John" }
{ "_id" : 2, "Name" : "Carol" }
{ "_id" : 3, "Name" : "Sam" }
{ "_id" : 4, "Name" : "David" }
Following is the query to implement multiple conditions in WHERE clause −
> db.multipleConditionDemo.remove({ $or: [ { _id: 2 }, { _id: 3 } ] });
WriteResult({ "nRemoved" : 2 })
Let us check the documents from the above collection once again −
> db.multipleConditionDemo.find().pretty();
This will produce the following output −
{ "_id" : 1, "Name" : "John" }
{ "_id" : 4, "Name" : "David" }Advertisements