![]() |
VOOZH | about |
The MongoDB $or operator matches documents that satisfy at least one of multiple conditions, making it ideal for flexible filtering in searches and data retrieval.
{ $or: [ { Expression1 }, { Expression2 }, ..., { ExpressionN } ] }Let's first set up MongoDB and insert sample data for demonstration. We will be working with:
Example: Retrieve all contributor documents where the branch is ECE or the joining year is 2017
db.contributor.find({$or: [{ branch: "ECE" }, { joiningYear: 2017 }]})Output:
The $or operator can query nested fields, letting you filter documents using multiple conditions within embedded objects.
Example: Retrieve contributor's where either age is 24 or State is Texas
db.contributor.find({$or: [{"personal.age": 24}, {"personal.state": "Texas"}]})Output:
The $or operator can match values in arrays, returning documents where at least one array element meets a condition.
Example: Retrieve contributors who know either "Java" or "C"
db.contributor.find({$or: [{ language: { $in: ["Java"] } }, { language: { $in: ["C"] } }]})Output:
MongoDB lets you combine $or with $and, $nor, and $not to build flexible, complex queries.
Example: Retrieve contributors whose branch is ECE or personal state is Finance Department and are at least 25 years old
db.contributor.find({$and: [{ $or: [{ branch: "ECE" }, { joiningYear: 2017 }] }, { $or: [{ "personal.state": "Texas" }, { "personal.age": 25 }]}]})Output:
Optimizing $or queries with proper indexing helps MongoDB avoid full collection scans and improves query performance.
Use the $or operator when documents can match any one of multiple conditions.