Find All Documents
In this step, you'll learn how to retrieve all documents from a MongoDB collection using the find()
method. This is a fundamental skill for working with MongoDB databases.
First, let's start the MongoDB shell and create a sample database with some documents to work with:
mongosh
Once in the MongoDB shell, create a new database and add some sample data:
use bookstore
db.books.insertMany([
{ title: "Python Basics", author: "John Smith", year: 2022 },
{ title: "MongoDB Essentials", author: "Jane Doe", year: 2023 },
{ title: "Web Development", author: "Alice Johnson", year: 2021 }
])
Now, to find all documents in the books
collection, use the find()
method without any parameters:
db.books.find();
You should see output similar to this:
[
{
_id: ObjectId("..."),
title: 'Python Basics',
author: 'John Smith',
year: 2022
},
{
_id: ObjectId("..."),
title: 'MongoDB Essentials',
author: 'Jane Doe',
year: 2023
},
{
_id: ObjectId("..."),
title: 'Web Development',
author: 'Alice Johnson',
year: 2021
}
]
Let's break down what happened:
use bookstore
creates or switches to the bookstore database
db.books.insertMany()
adds multiple documents to the books
collection
db.books.find()
retrieves all documents in the collection
If you want a more readable output, you can use pretty()
:
db.books.find().pretty();
This will format the output with line breaks and indentation, making it easier to read.