Insert Single Document
Welcome to the MongoDB Hands-on Lab! In this first step, we'll explore how to insert documents into a MongoDB collection. MongoDB is a powerful NoSQL database that stores data in flexible, JSON-like documents, making it incredibly versatile for various application needs.
Understanding MongoDB Basics
Before we begin, let's briefly discuss what we'll be doing. We'll create a bookstore database and learn how to insert documents representing books. This will help you understand the fundamental document insertion techniques in MongoDB.
Connect to MongoDB
First, open a terminal and connect to MongoDB using mongosh
:
mongosh
You should see the MongoDB shell prompt, indicating a successful connection.
Create a Database and Collection
Let's create a new database called bookstore
and a collection named books
:
use bookstore
db.createCollection("books")
Example output:
switched to db bookstore
{ ok: 1 }
Insert a Single Document
Now, let's insert a single document representing a book into the books
collection:
db.books.insertOne({
title: "The Great Gatsby",
author: "F. Scott Fitzgerald",
year: 1925,
genres: ["Classic", "Fiction"]
})
Example output:
{
acknowledged: true,
insertedId: ObjectId("...unique-object-id...")
}
Notice how MongoDB automatically generates a unique _id
for each document. This helps ensure each document can be uniquely identified in the collection.