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 $or operator returns documents matching any of the specified conditions.
  • You can combine multiple field conditions within a single $or array.
  • Use $or in early pipeline stages like $match to 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.

Updated on: 2026-03-15T00:10:17+05:30

285 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements