How to Use $or Operator in MongoDB Queries
In MongoDB, use the
$or operator to find documents that match at least one condition from an array of conditions. It takes an array of query expressions and returns documents where any of these expressions are true.Syntax
The $or operator takes an array of query objects. Each object is a condition to check. MongoDB returns documents that satisfy any of these conditions.
{ $or: [ { condition1 }, { condition2 }, ... ] }- Each
conditionis a standard MongoDB query expression.
json
{
"$or": [
{ "<field1>": "<value1>" },
{ "<field2>": "<value2>" },
...
]
}Example
This example finds users who live in either 'New York' or have the role 'admin'. It shows how $or returns documents matching any of the conditions.
mongodb
db.users.find({
$or: [
{ city: "New York" },
{ role: "admin" }
]
})Output
[
{ "_id": 1, "name": "Alice", "city": "New York", "role": "user" },
{ "_id": 3, "name": "Charlie", "city": "Boston", "role": "admin" }
]
Common Pitfalls
Common mistakes include:
- Using
$orwith a single condition array item, which is unnecessary. - Not wrapping each condition in its own object inside the array.
- Mixing
$orwith other operators incorrectly.
Always ensure each condition is a valid query object inside the $or array.
mongodb
/* Wrong: conditions not wrapped in objects */ db.users.find({ $or: [ { city: "New York" }, { role: "admin" } ] }) /* Right: each condition is an object */ db.users.find({ $or: [ { city: "New York" }, { role: "admin" } ] })
Quick Reference
- $or: Matches documents where at least one condition is true.
- Use an array of objects, each with a field and value condition.
- Combine with other operators for complex queries.
Key Takeaways
Use $or with an array of condition objects to match any condition.
Each condition inside $or must be a valid query object.
Avoid using $or with only one condition; it's unnecessary.
Combine $or with other operators for flexible queries.
Check syntax carefully to avoid common mistakes with $or.