findOne vs find: Cursors Explained
Learners will retrieve documents using findOne and iterate a find cursor, understanding how MongoDB streams large result sets.
Two Ways to Read Documents
MongoDB provides two primary methods for reading documents from a collection:
- findOne(filter, projection) — retrieves the first document matching the filter and returns it as a plain document object (or
nullif nothing matches) - find(filter, projection) — retrieves all matching documents and returns a cursor, a lazy iterator that streams results from the server one batch at a time
Understanding when to use each method—and how cursors work—is fundamental to writing efficient MongoDB queries.
findOne: Simple and Direct
findOne() is the simplest way to retrieve a single document. It returns the first document that matches the filter, or null if no document matches. If multiple documents match, MongoDB returns whichever it encounters first in its internal order—add a .sort() before calling this if you need a specific one.
Common use cases for findOne: looking up a user by email, fetching a product by SKU, or checking if a record exists. Because it returns a plain object rather than a cursor, you use the result directly without iteration.
// findOne by _id (most common lookup)
const user = await db.collection('users').findOne(
{ _id: ObjectId('64a2f3b1...') }
);
if (!user) {
throw new Error('User not found');
}
console.log(user.name); // 'Alice'
// findOne with a filter
const admin = await db.collection('users').findOne({ role: 'admin' });
// Returns ONE admin doc (undefined order), or nullAll lessons in this course
- insertOne and insertMany
- findOne vs find: Cursors Explained
- Querying Nested Fields and Arrays
- Reading Documents With the Node.js Driver