Introduction to find()
The find() method is the primary way to retrieve documents from a MongoDB collection. It accepts an optional filter document that specifies which documents to return and an optional projection to control which fields appear in the results.
Unlike SQL's SELECT statement, find() works with JSON-like documents and returns a cursor that you can iterate over.
Basic Syntax
To retrieve all documents from a collection, call find() without any arguments:
// Return all documents in the "users" collection
db.users.find()
// Equivalent with an empty filter
db.users.find({})Filtering Documents
Pass a filter document to retrieve only matching documents. Each key-value pair in the filter acts as an equality condition:
// Find users in the "engineering" department
db.users.find({ department: "engineering" })
// Find users with a specific age AND department
db.users.find({ department: "engineering", age: 30 })When you specify multiple fields in the filter, MongoDB treats them as an implicit AND -- all conditions must be true for a document to match.
Using findOne()
If you only need a single matching document, use findOne(). It returns the document directly instead of a cursor:
// Return the first user with email "alice@example.com"
db.users.findOne({ email: "alice@example.com" })Sorting and Limiting Results
Chain sort(), limit(), and skip() onto a cursor to control the order and number of results:
// Get the 10 newest users, sorted by createdAt descending
db.users.find().sort({ createdAt: -1 }).limit(10)
// Pagination: skip the first 20 results, return the next 10
db.users.find().sort({ name: 1 }).skip(20).limit(10)Counting Documents
Use countDocuments() to count documents matching a filter:
// Count all active users
db.users.countDocuments({ status: "active" })
// Count all documents in the collection
db.users.countDocuments({})Key Takeaways
find()returns a cursor;findOne()returns a single document.- Pass a filter document to narrow results -- multiple fields are combined with implicit AND.
- Use
sort(),limit(), andskip()for ordering and pagination. countDocuments()gives you the number of matching documents.
Try this query in UnifySQL
Write, optimize, and collaborate on MongoDB queries with AI assistance.
Start Free