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
MongoDB query to implement OR operator in find()
The MongoDB $or operator allows you to perform logical OR operations in find() queries. It matches documents that satisfy at least one of the specified conditions in an array of query expressions.
Syntax
db.collection.find({
$or: [
{ field1: value1 },
{ field2: value2 },
{ field3: value3 }
]
});
Sample Data
db.demo78.insertMany([
{ "Name1": "Chris", "Name2": "Mike" },
{ "Name1": "Bob", "Name2": "Carol" },
{ "Name1": "David", "Name2": "Sam" },
{ "Name1": "Jace", "Name2": "John" }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e2bd99c71bf0181ecc4228f"),
ObjectId("5e2bd9ac71bf0181ecc42290"),
ObjectId("5e2bd9b671bf0181ecc42291"),
ObjectId("5e2bd9bf71bf0181ecc42292")
]
}
Display all documents from the collection ?
db.demo78.find();
{ "_id": ObjectId("5e2bd99c71bf0181ecc4228f"), "Name1": "Chris", "Name2": "Mike" }
{ "_id": ObjectId("5e2bd9ac71bf0181ecc42290"), "Name1": "Bob", "Name2": "Carol" }
{ "_id": ObjectId("5e2bd9b671bf0181ecc42291"), "Name1": "David", "Name2": "Sam" }
{ "_id": ObjectId("5e2bd9bf71bf0181ecc42292"), "Name1": "Jace", "Name2": "John" }
Example: Using $or Operator
Find documents where Name1 is "Bob" OR Name2 is "John" ?
db.demo78.find({
$or: [
{ "Name1": "Bob" },
{ "Name2": "John" }
]
});
{ "_id": ObjectId("5e2bd9ac71bf0181ecc42290"), "Name1": "Bob", "Name2": "Carol" }
{ "_id": ObjectId("5e2bd9bf71bf0181ecc42292"), "Name1": "Jace", "Name2": "John" }
Key Points
- The
$oroperator takes an array of conditions and returns documents matching any of them. - Each condition in the array is a separate query expression.
- MongoDB evaluates conditions from left to right and stops at the first match for efficiency.
Conclusion
The $or operator enables flexible querying by matching documents that satisfy at least one condition from an array of query expressions. It's essential for implementing complex search logic in MongoDB applications.
Advertisements
