How to Use find() in MongoDB: Syntax and Examples
In MongoDB, use the
find() method to retrieve documents from a collection that match a query filter. It returns a cursor to the matching documents, which you can iterate or convert to an array. You can specify query conditions inside find() to filter results.Syntax
The find() method has this basic syntax:
db.collection.find(query, projection)
query is an object specifying the search criteria (filter).
projection is optional and specifies which fields to include or exclude in the results.
mongodb
db.collection.find({ field: value }, { field1: 1, field2: 0 })Example
This example shows how to find all documents in the users collection where the age is greater than 25, and only return the name and age fields:
mongodb
db.users.find({ age: { $gt: 25 } }, { name: 1, age: 1, _id: 0 })Output
[
{ "name": "Alice", "age": 30 },
{ "name": "Bob", "age": 28 }
]
Common Pitfalls
Common mistakes when using find() include:
- Not using a query filter, which returns all documents and can be slow on large collections.
- Forgetting to exclude the
_idfield if you don't want it in results (use{ _id: 0 }in projection). - Using incorrect query operators or syntax, causing no results or errors.
Example of a wrong and right way:
mongodb
/* Wrong: returns all documents without filter */ db.users.find() /* Right: filter by age greater than 25 */ db.users.find({ age: { $gt: 25 } })
Quick Reference
| Usage | Description |
|---|---|
| db.collection.find(query) | Find documents matching query filter |
| db.collection.find(query, projection) | Find documents and specify fields to return |
| { field: value } | Match documents where field equals value |
| { field: { $gt: value } } | Match documents where field is greater than value |
| { _id: 0 } | Exclude _id field from results |
Key Takeaways
Use db.collection.find() with a query object to filter documents.
Specify projection to control which fields appear in results.
Always use query filters to avoid returning all documents unintentionally.
Remember to exclude _id if you don't want it in the output.
Use correct MongoDB query operators like $gt, $lt for conditions.