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
How to implement MongoDB $or operator
The $or operator in MongoDB performs a logical OR operation on an array of expressions and returns documents that match at least one of the specified conditions.
Syntax
db.collection.find({
$or: [
{ "field1": value1 },
{ "field2": value2 }
]
});
Create Sample Data
db.orOperatorDemo.insertMany([
{ "StudentNames": ["John", "Carol", "Sam"] },
{ "StudentNames": ["Robert", "Chris", "David"] },
{ "StudentNames": ["John"] }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5cd6b80a6d78f205348bc61b"),
ObjectId("5cd6b8266d78f205348bc61c"),
ObjectId("5cd6b8346d78f205348bc61d")
]
}
View Sample Data
db.orOperatorDemo.find().pretty();
{
"_id": ObjectId("5cd6b80a6d78f205348bc61b"),
"StudentNames": [
"John",
"Carol",
"Sam"
]
}
{
"_id": ObjectId("5cd6b8266d78f205348bc61c"),
"StudentNames": [
"Robert",
"Chris",
"David"
]
}
{
"_id": ObjectId("5cd6b8346d78f205348bc61d"),
"StudentNames": [
"John"
]
}
Example: Using $or Operator
Find documents where StudentNames contains either "Carol" OR "John" ?
db.orOperatorDemo.find({
$or: [
{ "StudentNames": "Carol" },
{ "StudentNames": "John" }
]
}).pretty();
{
"_id": ObjectId("5cd6b80a6d78f205348bc61b"),
"StudentNames": [
"John",
"Carol",
"Sam"
]
}
{
"_id": ObjectId("5cd6b8346d78f205348bc61d"),
"StudentNames": [
"John"
]
}
Key Points
- The
$oroperator accepts an array of expressions - Returns documents that match any one of the conditions
- Each condition in the array is evaluated independently
Conclusion
The $or operator provides flexible querying by matching documents against multiple conditions. Use it when you need to retrieve documents that satisfy at least one of several criteria.
Advertisements
