Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Implement multiple conditions in MongoDB?
To implement multiple conditions in MongoDB queries, use logical operators like $and, $or, and $nor to combine different criteria. These operators allow you to create complex queries that match documents based on multiple field conditions.
Syntax
// AND condition (all conditions must be true)
db.collection.find({ $and: [{ condition1 }, { condition2 }] });
// OR condition (any condition can be true)
db.collection.find({ $or: [{ condition1 }, { condition2 }] });
// NOR condition (none of the conditions should be true)
db.collection.find({ $nor: [{ condition1 }, { condition2 }] });
Sample Data
db.multipleConditionDemo.insertMany([
{ "_id": 1, "Name": "John", "Age": 25, "City": "New York" },
{ "_id": 2, "Name": "Carol", "Age": 30, "City": "London" },
{ "_id": 3, "Name": "Sam", "Age": 25, "City": "Paris" },
{ "_id": 4, "Name": "David", "Age": 35, "City": "New York" }
]);
{
"acknowledged": true,
"insertedIds": [1, 2, 3, 4]
}
Display All Documents
db.multipleConditionDemo.find();
{ "_id": 1, "Name": "John", "Age": 25, "City": "New York" }
{ "_id": 2, "Name": "Carol", "Age": 30, "City": "London" }
{ "_id": 3, "Name": "Sam", "Age": 25, "City": "Paris" }
{ "_id": 4, "Name": "David", "Age": 35, "City": "New York" }
Method 1: Using $or Operator
Find documents where either _id is 2 OR _id is 3 ?
db.multipleConditionDemo.find({ $or: [{ "_id": 2 }, { "_id": 3 }] });
{ "_id": 2, "Name": "Carol", "Age": 30, "City": "London" }
{ "_id": 3, "Name": "Sam", "Age": 25, "City": "Paris" }
Method 2: Using $and Operator
Find documents where Age is 25 AND City is "New York" ?
db.multipleConditionDemo.find({ $and: [{ "Age": 25 }, { "City": "New York" }] });
{ "_id": 1, "Name": "John", "Age": 25, "City": "New York" }
Method 3: Removing with Multiple Conditions
Remove documents where either _id is 2 OR _id is 3 ?
db.multipleConditionDemo.remove({ $or: [{ "_id": 2 }, { "_id": 3 }] });
WriteResult({ "nRemoved": 2 })
Verify the remaining documents ?
db.multipleConditionDemo.find();
{ "_id": 1, "Name": "John", "Age": 25, "City": "New York" }
{ "_id": 4, "Name": "David", "Age": 35, "City": "New York" }
Key Points
-
$orreturns documents that match any of the specified conditions. -
$andreturns documents that match all of the specified conditions. - Multiple conditions can be used in find(), update(), and remove() operations.
Conclusion
MongoDB's logical operators $or, $and, and $nor enable powerful multiple condition queries. These operators work across all MongoDB operations including find, update, and remove for flexible document filtering.
Advertisements
