How to Find Documents with Condition in MongoDB
In MongoDB, use the
find() method with a condition object to retrieve documents that match specific criteria. The condition is a JSON-like object specifying field-value pairs or operators to filter results.Syntax
The find() method takes a condition object as its first argument. This object defines the criteria documents must meet to be returned.
db.collection.find(condition): Finds documents matchingcondition.condition: A JSON object with field names and values or operators.
mongodb
db.collection.find({ field: value })Example
This example finds all users with the age of 25 in the users collection.
mongodb
db.users.find({ age: 25 })Output
[
{ "_id": ObjectId("..."), "name": "Alice", "age": 25 },
{ "_id": ObjectId("..."), "name": "Bob", "age": 25 }
]
Common Pitfalls
Common mistakes include:
- Using incorrect field names that do not exist in documents.
- Passing a value without wrapping it in an object for conditions.
- Forgetting to use operators like
$gtfor greater than comparisons.
mongodb
/* Wrong: Trying to find age greater than 25 without operator */ db.users.find({ age: 25 }) /* Right: Using $gt operator for age greater than 25 */ db.users.find({ age: { $gt: 25 } })
Quick Reference
| Operator | Description | Example |
|---|---|---|
| $eq | Equals | { age: { $eq: 25 } } |
| $gt | Greater than | { age: { $gt: 25 } } |
| $lt | Less than | { age: { $lt: 25 } } |
| $in | In array of values | { status: { $in: ["A", "B"] } } |
| $ne | Not equal | { age: { $ne: 25 } } |
Key Takeaways
Use the find() method with a condition object to filter documents in MongoDB.
Conditions are JSON objects specifying field-value pairs or operators like $gt, $lt.
Always use correct field names and operators to avoid empty results.
Operators like $eq, $gt, $lt help create flexible queries.
Check your query syntax carefully to prevent common mistakes.