Find Documents

Find Documents in MongoDB

Reading data is the most common database task. MongoDB provides flexible query methods to find data. The find() method retrieves documents easily.

Finding All Documents

To get everything in a collection, use find(). Pass an empty object {} as the query filter. It returns a cursor pointing to all results.

Finding a Single Document

Use findOne() to grab exactly one result. It returns the actual document object, not a cursor. It is perfect for retrieving a specific user profile.

Applying Query Filters

Filters narrow down your results. You pass a condition object to find({ key: value }). MongoDB will return documents matching those fields exactly.

Formatting the Output

The MongoDB shell uses .pretty() for readability. Chaining .pretty() makes the JSON easy to read. It adds spaces and line breaks to the output.

Find Examples:

// Find all users
db.users.find({});

// Find one specific user by name db.users.findOne({ name: "John Doe" });

// Find users with a specific age and format output db.users.find({ age: 25 }).pretty();

Understanding Cursors

The find() method does not return all data at once. It returns a pointer, called a cursor. The cursor streams data in small batches.

Iterating Cursors

In drivers, you iterate over the cursor. You can use methods like toArray(). This converts the streamed results into a standard array.

Projections

Projections limit which fields are returned. Pass a second object to find(). Use 1 to include a field, and 0 to hide it.

Summary

Use find() for multiple items and findOne() for single items. Always filter to keep database load small. Use projections to reduce network bandwidth.

Exercise

What does the find() method return when you execute it?