Open In App

MongoDB OR operator ( $or )

Last Updated : 03 Feb, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

MongoDB provides various logical query operators, and the $or operator is one of the most powerful among them. It is used to retrieve documents that match at least one of multiple specified conditions, making it ideal for scenarios where multiple filtering criteria need to be considered.

In this article, we will explore the $or operator in-depth, covering its syntax, usage in various queries, performance considerations, and advanced use cases. By the end of this guide, we will have a clear understanding of how to effectively use the $or operator to optimize queries and retrieve relevant data efficiently.

What is the $or Operator in MongoDB?

The $or operator is a logical query operator that allows you to specify multiple conditions in an array. MongoDB returns documents that satisfy at least one of these conditions. By using the $or operator, we can simplify complex queries and avoid writing multiple separate queries, improving both efficiency and readability. It is commonly used in search filters, user authentication, and data retrieval operations where multiple conditions can lead to valid results.

Key Features of $or:

  • It can be used in find(), update(), and aggregation queries.
  • It is compatible with text searches, GeoSpatial queries, and sorting operations.
  • MongoDB evaluates each condition in the $or array independently.
  • If indexes exist for the fields being queried, MongoDB performs index scans instead of a collection scan, improving query efficiency.
  • The $or operator can be nested inside other logical operators for more complex queries.

Syntax:  

{ $or: [ { Expression1 }, { Expression2 }, …, { ExpressionN } ] }

Each condition inside the $or array acts as an independent filter, and documents that satisfy any of the conditions are returned.

Setting Up MongoDB and Sample Data

Before exploring practical examples, let’s first set up MongoDB and insert sample data for demonstration. In this guide, we will be working with:

  • Database: GeeksforGeeks 
  • Collection: contributor 
  • Document: three documents that contain the details of the contributors in the form of field-value pairs.

This setup will help illustrate how the $or operator works in real-world queries. Let’s begin by inserting sample data into our collection

Examples of Using $or in Queries

The $or operator can be used in various scenarios to filter documents based on multiple conditions. It is commonly applied in find(), update(), and aggregation queries to retrieve relevant data efficiently. Below are some practical examples demonstrating its usage in different contexts.

Example 1: Find Employees whose branch is ECE or Joining Year is 2017

In this example, we retrieve all employee documents where the branch is ECE or the joining year is 2017. The $or operator ensures that if a document satisfies either of the conditions, it will be included in the result.

Query:

db.contributor.find({
$or: [
{ branch: "ECE" },
{ joiningYear: 2017 }
]
}).pretty();

Output

Explanation:

  • The query searches the contributor collection for employees who either belong to the ECE branch or have a joining year of 2017.
  • MongoDB evaluates both conditions independently and returns documents that meet at least one of them.

Matching Values in Nested/Embedded Documents Using $or Operator

The $or operator can also be used to query nested or embedded documents, allowing you to filter documents based on multiple conditions within subfields. This is particularly useful when dealing with structured data where attributes are stored inside an embedded object.

Example 3: Find Employees Where Either Age is 24 or State is Delhi

In this example, we retrieve employee documents where either the age is 24 or the state is Delhi. The $or operator ensures that if an employee meets at least one of these conditions, their document will be included in the query results.

Query:

 db.contributor.find({$or: [{"personal.age": 24}, 
{"personal.state": "Delhi"}]}).pretty()

Output

Explanation:

  • The query searches for employees who either have an age of 24 or reside in the state of Delhi.
  • Since age and state are stored inside the personal subdocument, we use dot notation (.) to access them within the query.
  • MongoDB evaluates both conditions independently and retrieves documents that satisfy at least one of them

Matching Values in an Array using $or Operator

The $or operator can be used to match values within arrays, allowing you to retrieve documents where at least one element in an array field meets a specified condition. This is useful when searching for records that contain at least one matching value in an array of values.

Example 4: Find Employees Who Know Either “Java” or “C”

In this example, we retrieve employee documents where at least one language in the language array matches either "Java" or "C". The $or operator ensures that employees proficient in either of these languages are included in the results

Query:

db.contributor.find({
$or: [
{ language: { $in: ["Java"] } },
{ language: { $in: ["C"] } }
]
}).pretty();

Output

Explanation:

  • This query searches the contributor collection for documents where the language array contains either "Java" or "C".
  • The $in operator is used within the $or conditions to check if at least one of the specified values exists in the language array.
  • MongoDB returns documents where an employee knows Java or knows C, even if they know additional languages

Combining $or with Other Logical Operators

MongoDB allows combining $or with other logical operators like $and, $nor, and $not to create more complex queries. This helps in filtering documents based on multiple conditions while maintaining flexibility in query execution.

Example: Find Employees Who Are in IT or Finance Department and Are at Least 25 Years Old

db.employees.find({
$and: [
{ $or: [ { department: "IT" }, { department: "Finance" } ] },
{ age: { $gte: 25 } }
]
});

Explanation:

  • The $or operator ensures that employees belong to either the IT or Finance department.
  • The $and operator ensures that only employees aged 25 or above are included in the results.
  • MongoDB first evaluates the $or conditions, then filters the results further using $and

Performance Considerations for $or Queries

  • Indexing: If all conditions in $or use indexed fields, MongoDB performs index scans instead of a full collection scan, which improves query speed.
  • Execution Strategy: If indexes exist on individual fields, MongoDB can use the best execution plan for each query condition.
  • Compound Indexes: Consider using compound indexes if frequent $or queries involve the same fields.

When to Use $or in MongoDB?

  • We need results matching any of multiple conditions.
  • Performing complex queries on nested or embedded documents.
  • Filtering documents that match different values in an array field.

Conclusion

The $or operator in MongoDB is a powerful tool for querying documents that match at least one of multiple conditions. It can be used in various ways, from basic queries to complex nested and indexed queries. $or helps retrieve documents meeting multiple conditions efficiently. It works with nested documents, arrays, and combined logical queries. Optimizing indexes can significantly improve performance. By mastering $or, we can write more flexible and efficient queries in MongoDB

FAQs

What is $or in MongoDB?

The $or operator is used to perform logical OR queries, returning documents that match at least one of the specified conditions.
db.collection.find({ $or: [{ age: 25 }, { city: “London” }] });

What is $set used for in MongoDB?

The $set operator is used in the update operation to modify or add fields in a document. If the field does not exist, it creates a new one.
db.collection.updateOne({ name: “John” }, { $set: { age: 30 } });

Why do we use $in in MongoDB?

The $in operator is used to match documents where a field’s value is within a specified array of values.
Example: db.collection.find({ category: { $in: [“electronics”, “furniture”] } });



Next Article
Article Tags :

Similar Reads

three90RightbarBannerImg