MongoDB query with an 'or' condition?

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 conditions. It's useful when you need to query documents based on multiple alternative criteria.

Syntax

db.collection.find({
    $or: [
        { field1: value1 },
        { field2: value2 },
        { field3: { $operator: value3 } }
    ]
});

Sample Data

Let's create a collection with sample documents to demonstrate OR conditions ?

db.orConditionDemo.insertMany([
    {
        "CustomerName": "Larry",
        "ShippingDate": new ISODate("2018-01-29")
    },
    {
        "CustomerName": "Mike",
        "ShippingDate": new ISODate("2019-04-13")
    },
    {
        "CustomerName": "Bob",
        "ShippingDate": new ISODate("2019-02-21")
    },
    {
        "CustomerName": "David",
        "ShippingDate": new ISODate("2019-03-15")
    },
    {
        "CustomerName": "John",
        "ShippingDate": new ISODate("2019-03-19")
    }
]);

Display all documents from the collection ?

db.orConditionDemo.find().pretty();
{
    "_id" : ObjectId("5c8ec5262f684a30fbdfd56a"),
    "CustomerName" : "Larry",
    "ShippingDate" : ISODate("2018-01-29T00:00:00Z")
}
{
    "_id" : ObjectId("5c8ec5362f684a30fbdfd56b"),
    "CustomerName" : "Mike",
    "ShippingDate" : ISODate("2019-04-13T00:00:00Z")
}
{
    "_id" : ObjectId("5c8ec5422f684a30fbdfd56c"),
    "CustomerName" : "Bob",
    "ShippingDate" : ISODate("2019-02-21T00:00:00Z")
}
{
    "_id" : ObjectId("5c8ec5532f684a30fbdfd56d"),
    "CustomerName" : "David",
    "ShippingDate" : ISODate("2019-03-15T00:00:00Z")
}
{
    "_id" : ObjectId("5c8ec56c2f684a30fbdfd56e"),
    "CustomerName" : "John",
    "ShippingDate" : ISODate("2019-03-19T00:00:00Z")
}

Example: OR Condition Query

Find documents where ShippingDate is greater than or equal to current date OR ShippingDate is null ?

db.orConditionDemo.find({
    $or: [
        { ShippingDate: { $gte: new ISODate() } },
        { ShippingDate: null }
    ]
}).pretty();
{
    "_id" : ObjectId("5c8ec5362f684a30fbdfd56b"),
    "CustomerName" : "Mike",
    "ShippingDate" : ISODate("2019-04-13T00:00:00Z")
}
{
    "_id" : ObjectId("5c8ec56c2f684a30fbdfd56e"),
    "CustomerName" : "John",
    "ShippingDate" : ISODate("2019-03-19T00:00:00Z")
}

More Examples

Find customers named "Larry" OR "Bob" ?

db.orConditionDemo.find({
    $or: [
        { CustomerName: "Larry" },
        { CustomerName: "Bob" }
    ]
});

Conclusion

The $or operator allows flexible querying by matching documents against multiple conditions. Use it when you need to find documents that satisfy at least one of several criteria, making it essential for complex filtering operations.

Updated on: 2026-03-15T00:13:36+05:30

520 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements