Connect to MongoDB and Find All Documents
In this first step, you will connect to the MongoDB server, create a database and a collection, insert some sample data, and then retrieve all the documents from that collection. This is the starting point for any database interaction.
First, open your terminal and start the MongoDB Shell by running the mongosh command.
mongosh
Your terminal prompt will change to indicate that you are now inside the MongoDB Shell, ready to execute database commands.
Next, switch to a new database named bookstore. If the database does not exist, MongoDB will create it when you first store data.
use bookstore
Now, let's insert some documents into a new collection called books. A collection is a group of MongoDB documents, similar to a table in a relational database. The insertMany() method allows you to add multiple documents at once.
db.books.insertMany([
{ title: "Python Basics", author: "John Smith", year: 2022, stock: 15 },
{ title: "MongoDB Essentials", author: "Jane Doe", year: 2023, stock: 8 },
{ title: "Web Development", author: "Alice Johnson", year: 2021, stock: 20 }
]);
After executing the command, you will see a confirmation that the documents were successfully inserted.
To retrieve and view all documents in the books collection, use the find() method without any arguments.
db.books.find();
The output will list all three documents you just inserted. Each document has an _id field, which is a unique identifier automatically added by MongoDB.
[
{
_id: ObjectId("..."),
title: 'Python Basics',
author: 'John Smith',
year: 2022,
stock: 15
},
{
_id: ObjectId("..."),
title: 'MongoDB Essentials',
author: 'Jane Doe',
year: 2023,
stock: 8
},
{
_id: ObjectId("..."),
title: 'Web Development',
author: 'Alice Johnson',
year: 2021,
stock: 20
}
]