Evaluate one of more values from a MongoDB collection with documents

To evaluate one or more values from a MongoDB collection, use the $or operator with the find() method. The $or operator performs a logical OR operation on an array of expressions and returns documents that match at least one of the conditions.

Syntax

db.collection.find({
    $or: [
        { "field1": "value1" },
        { "field2": "value2" },
        { "fieldN": "valueN" }
    ]
});

Sample Data

Let us create a collection with student documents:

db.demo174.insertMany([
    { "StudentName": "Chris", "CountryName": "US" },
    { "StudentName": "David", "CountryName": "UK" },
    { "StudentName": "Bob", "CountryName": "AUS" }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e383c709e4f06af551997e5"),
        ObjectId("5e383c779e4f06af551997e6"),
        ObjectId("5e383c7e9e4f06af551997e7")
    ]
}

Display all documents from the collection:

db.demo174.find();
{ "_id": ObjectId("5e383c709e4f06af551997e5"), "StudentName": "Chris", "CountryName": "US" }
{ "_id": ObjectId("5e383c779e4f06af551997e6"), "StudentName": "David", "CountryName": "UK" }
{ "_id": ObjectId("5e383c7e9e4f06af551997e7"), "StudentName": "Bob", "CountryName": "AUS" }

Example: Find Documents with Multiple Criteria

Find documents where the student name is "David" OR the country is "US":

db.demo174.find({
    $or: [
        { "StudentName": "David" },
        { "CountryName": "US" }
    ]
});
{ "_id": ObjectId("5e383c709e4f06af551997e5"), "StudentName": "Chris", "CountryName": "US" }
{ "_id": ObjectId("5e383c779e4f06af551997e6"), "StudentName": "David", "CountryName": "UK" }

Key Points

  • The $or operator returns documents that match any of the specified conditions.
  • Each condition in the $or array is evaluated independently.
  • Use $or when you need to find documents that satisfy multiple alternative criteria.

Conclusion

The $or operator provides an efficient way to query documents that match one or more conditions. It's essential for implementing flexible search functionality in MongoDB applications.

Updated on: 2026-03-15T01:39:02+05:30

161 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements