Reading Documents with find() and findOne()
MongoDB provides find() and findOne() for retrieving documents.
find()
db.users.find({ active: true });
The find() method returns a cursor representing the matching documents. The shell displays results according to its cursor-display behavior.
In application code, a cursor can be iterated or consumed using the APIs provided by the MongoDB driver.
findOne()
db.users.findOne({ email: "arun@example.com" });
findOne() returns one matching document or null if no document matches.
If several documents match, do not assume that the returned document is the newest, oldest, or otherwise preferred document unless you explicitly define a sort order.
Empty filter
db.users.find({});
An empty filter matches all documents in the collection.
This is useful for exploration, but production queries should generally include appropriate filters and pagination or limits where necessary.
Querying nested fields
db.users.find({ "address.city": "Chennai" });
Dot notation allows you to query fields inside embedded documents.
Querying arrays
db.users.find({ skills: "MongoDB" });
For an array field, this matches documents whose array contains the specified value.
Sorting results
db.users.find({ active: true }).sort({ createdAt: -1 });
The sort order -1 means descending and 1 means ascending.
For deterministic pagination, use a sort order that includes a unique tie-breaker, such as _id, especially when multiple documents may have the same primary sort value.
Limiting results
db.users.find({ active: true })
.sort({ createdAt: -1, _id: -1 })
.limit(20);
This returns at most 20 matching documents, ordered by creation time and identifier.
Cursors and large datasets
A cursor allows results to be processed incrementally rather than materializing every document at once. This is important when working with large collections.
In the Node.js driver, use cursor iteration or an appropriate cursor API when handling large result sets. Avoid calling toArray() on an unbounded result set if the result may exceed available application memory.
db.readDemo.insertMany([
{ name: "Arun", age: 22, active: true },
{ name: "Meera", age: 24, active: true },
{ name: "Ravi", age: 25, active: false }
]);
// Find all active users.
db.readDemo.find({ active: true });
// Retrieve one matching document.
db.readDemo.findOne({ name: "Arun" });
// Sort and limit the result set.
db.readDemo.find({ active: true })
.sort({ age: -1, _id: -1 })
.limit(10);- find() returns a cursor for matching documents.
- findOne() returns one document or null.
- An empty filter matches all documents.
- Sorting is required when a particular result order matters.
- Cursors help process large result sets without loading every document into memory.
What does findOne() return when no document matches its filter?