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
Fetch multiple documents in MongoDB query with OR condition?
To fetch multiple documents in MongoDB using OR condition, use the $or operator which performs a logical OR operation on an array of expressions and selects documents that satisfy at least one of the expressions.
Syntax
db.collection.find({
$or: [
{ field1: value1 },
{ field2: value2 },
{ field3: value3 }
]
});
Sample Data
db.demo362.insertMany([
{ "ClientName": "John", "ClientProject": "School Management System" },
{ "ClientName": "David", "ClientProject": "Library Management System" },
{ "ClientName": "Mike", "ClientProject": "Event Tracker" },
{ "ClientName": "Carol", "ClientProject": "Hospital Management System" }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e56a77454a481fef8ec7a1c"),
ObjectId("5e56a78454a481fef8ec7a1d"),
ObjectId("5e56a7a054a481fef8ec7a1e"),
ObjectId("5e56a7b754a481fef8ec7a1f")
]
}
Display all documents from the collection ?
db.demo362.find();
{ "_id": ObjectId("5e56a77454a481fef8ec7a1c"), "ClientName": "John", "ClientProject": "School Management System" }
{ "_id": ObjectId("5e56a78454a481fef8ec7a1d"), "ClientName": "David", "ClientProject": "Library Management System" }
{ "_id": ObjectId("5e56a7a054a481fef8ec7a1e"), "ClientName": "Mike", "ClientProject": "Event Tracker" }
{ "_id": ObjectId("5e56a7b754a481fef8ec7a1f"), "ClientName": "Carol", "ClientProject": "Hospital Management System" }
Example: Fetch Documents with OR Condition
Fetch documents where ClientName is "John" OR ClientProject is "Event Tracker" ?
db.demo362.find({
$or: [
{ "ClientName": "John" },
{ "ClientProject": "Event Tracker" }
]
});
{ "_id": ObjectId("5e56a77454a481fef8ec7a1c"), "ClientName": "John", "ClientProject": "School Management System" }
{ "_id": ObjectId("5e56a7a054a481fef8ec7a1e"), "ClientName": "Mike", "ClientProject": "Event Tracker" }
Key Points
- The
$oroperator takes an array of expressions as its value. - Documents matching any one of the conditions will be returned.
- Use
$orwhen you need flexible matching across different fields or values.
Conclusion
The $or operator enables flexible document retrieval by matching any of the specified conditions. It's essential for queries requiring multiple alternative criteria across different fields.
Advertisements
