Reading data is the most common database task. MongoDB provides flexible query methods to find data. The find() method retrieves documents easily.
To get everything in a collection, use find(). Pass an empty object {} as the query filter. It returns a cursor pointing to all results.
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.
Filters narrow down your results. You pass a condition object to find({ key: value }). MongoDB will return documents matching those fields exactly.
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 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();
The find() method does not return all data at once. It returns a pointer, called a cursor. The cursor streams data in small batches.
In drivers, you iterate over the cursor. You can use methods like toArray(). This converts the streamed results into a standard array.
Projections limit which fields are returned. Pass a second object to find(). Use 1 to include a field, and 0 to hide it.
Use find() for multiple items and findOne() for single items. Always filter to keep database load small. Use projections to reduce network bandwidth.
What does the find() method return when you execute it?