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 aggregation framework match OR is possible?
Yes, MongoDB aggregation framework supports the $or operator within the $match stage to match documents that satisfy at least one of multiple conditions. This allows you to create flexible filtering logic in your aggregation pipelines.
Syntax
db.collection.aggregate([
{
$match: {
$or: [
{ field1: value1 },
{ field2: value2 }
]
}
}
])
Sample Data
Let us create a collection with student documents ?
db.aggregationFrameworkWithOrMatchDemo.insertMany([
{
"StudentFirstName": "John",
"StudentLastName": "Smith",
"StudentAge": 23
},
{
"StudentFirstName": "Carol",
"StudentLastName": "Taylor",
"StudentAge": 24
},
{
"StudentFirstName": "David",
"StudentLastName": "Miller",
"StudentAge": 21
},
{
"StudentFirstName": "Bob",
"StudentLastName": "Taylor",
"StudentAge": 20
},
{
"StudentFirstName": "Robert",
"StudentLastName": "Smith",
"StudentAge": 20
},
{
"StudentFirstName": "Mike",
"StudentLastName": "Miller",
"StudentAge": 27
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("..."),
ObjectId("..."),
...
]
}
Example: Match Students with Smith or Miller Last Name
Use the $or operator within $match to find students with last name "Smith" or "Miller" ?
db.aggregationFrameworkWithOrMatchDemo.aggregate([
{
$match: {
$or: [
{ StudentLastName: "Smith" },
{ StudentLastName: "Miller" }
]
}
}
]);
{
"_id": ObjectId("..."),
"StudentFirstName": "John",
"StudentLastName": "Smith",
"StudentAge": 23
}
{
"_id": ObjectId("..."),
"StudentFirstName": "David",
"StudentLastName": "Miller",
"StudentAge": 21
}
{
"_id": ObjectId("..."),
"StudentFirstName": "Robert",
"StudentLastName": "Smith",
"StudentAge": 20
}
{
"_id": ObjectId("..."),
"StudentFirstName": "Mike",
"StudentLastName": "Miller",
"StudentAge": 27
}
Key Points
- The
$oroperator returns documents matching any of the specified conditions. - You can combine multiple field conditions within a single
$orarray. - Use
$orin early pipeline stages like$matchto leverage index optimization.
Conclusion
The MongoDB aggregation framework fully supports $or operations within the $match stage. This enables flexible document filtering by allowing multiple conditions where any one condition can satisfy the match criteria.
Advertisements
