How to Find All Documents in MongoDB Quickly and Easily
To find all documents in MongoDB, use the
find() method without any filter inside the collection. For example, db.collection.find() returns every document in that collection.Syntax
The basic syntax to find all documents in a MongoDB collection is:
db.collection.find(): Retrieves all documents from the specified collection.db: Refers to the current database.collection: The name of the collection you want to query.find(): The method that fetches documents; when called without arguments, it returns all documents.
mongodb
db.collection.find()
Example
This example shows how to find all documents in a collection named users. It prints each document to the console.
mongodb
use mydatabase // Insert sample documents db.users.insertMany([ { name: "Alice", age: 25 }, { name: "Bob", age: 30 }, { name: "Charlie", age: 35 } ]) // Find all documents const cursor = db.users.find() // Print each document cursor.forEach(doc => printjson(doc))
Output
{ "_id" : ObjectId("..."), "name" : "Alice", "age" : 25 }
{ "_id" : ObjectId("..."), "name" : "Bob", "age" : 30 }
{ "_id" : ObjectId("..."), "name" : "Charlie", "age" : 35 }
Common Pitfalls
Common mistakes when trying to find all documents include:
- Using
find({})is correct but sometimes people add incorrect filters that exclude documents. - Forgetting to iterate over the cursor to see results in the shell.
- Expecting
find()to return an array directly; it returns a cursor that you must iterate.
Example of a wrong approach and the right way:
mongodb
// Wrong: expecting an array directly const result = db.users.find() print(result) // prints cursor info, not documents // Right: iterate the cursor const cursor = db.users.find() cursor.forEach(doc => printjson(doc))
Quick Reference
| Command | Description |
|---|---|
| db.collection.find() | Finds all documents in the collection |
| db.collection.find({}) | Also finds all documents, empty filter |
| cursor.forEach(doc => printjson(doc)) | Prints each document from the cursor |
| db.collection.find().limit(5) | Finds first 5 documents only |
Key Takeaways
Use db.collection.find() without arguments to get all documents.
The find() method returns a cursor, not an array; iterate it to access documents.
Avoid adding filters if you want every document in the collection.
Use cursor methods like forEach() to process or print documents.
Remember to specify the correct collection name in your queries.