Introduction
In this lab, you will learn the fundamental techniques for inserting data into a MongoDB database. You will practice inserting single and multiple documents, handling potential errors, and verifying data integrity using the MongoDB shell (mongosh).
This lab focuses on the "Create" operation within CRUD (Create, Read, Update, Delete). You will build a simple bookstore database from scratch, gaining hands-on experience with essential data management tasks in a NoSQL environment. By the end, you will have a solid understanding of how to add and manage data effectively in MongoDB.
Insert a Single Document
In this first step, you will connect to the MongoDB server, create a database and a collection, and insert your first document. MongoDB stores data in flexible, JSON-like documents, which makes it easy to represent complex data structures.
First, connect to your local MongoDB instance using the MongoDB Shell. Open your terminal and run the following command:
mongosh
You will see a > prompt, indicating that you are now in the MongoDB Shell and connected to the database.
Next, switch to a new database named bookstore. If the database does not exist, MongoDB will create it for you when you first store data.
use bookstore
The output will confirm that you have switched to the bookstore database.
switched to db bookstore
Now, insert a single document into a new collection called books. A collection is a group of MongoDB documents, roughly equivalent to a table in a relational database. The insertOne() method adds a single document to the collection.
db.books.insertOne({
title: "The Great Gatsby",
author: "F. Scott Fitzgerald",
year: 1925,
genres: ["Classic", "Fiction"],
stock: 10
});
Upon successful insertion, MongoDB returns a document confirming the operation and providing the unique _id of the newly inserted document.
{
acknowledged: true,
insertedId: ObjectId("652f8d3e111a2b3c4d5e6f78")
}
The _id is a unique identifier automatically generated by MongoDB for every document, ensuring that each document in a collection can be uniquely identified.
Insert Multiple Documents
Inserting documents one by one can be inefficient. For adding multiple documents at once, MongoDB provides the insertMany() method. This is known as a bulk insert operation, which reduces the number of network round trips to the database.
In this step, you will add three more books to your books collection in a single command. Make sure you are still in the mongosh shell and have switched to the bookstore database.
Use the insertMany() method, passing an array of document objects.
db.books.insertMany([
{
title: "1984",
author: "George Orwell",
year: 1949,
genres: ["Dystopian", "Science Fiction"],
stock: 15
},
{
title: "To Kill a Mockingbird",
author: "Harper Lee",
year: 1960,
genres: ["Classic", "Fiction"],
stock: 5
},
{
title: "Pride and Prejudice",
author: "Jane Austen",
year: 1813,
genres: ["Romance", "Classic"],
stock: 12
}
]);
The output will confirm that the operation was acknowledged and will list the _id values for each of the three documents you inserted.
{
acknowledged: true,
insertedIds: {
'0': ObjectId("652f8e3e111a2b3c4d5e6f79"),
'1': ObjectId("652f8e3e111a2b3c4d5e6f7a"),
'2': ObjectId("652f8e3e111a2b3c4d5e6f7b")
}
}
To verify that the documents have been added, you can count the total number of documents in the collection.
db.books.countDocuments();
The result should be 4, representing the one document from the previous step and the three you just added.
4
Query and Verify Inserted Data
After inserting data, the next logical step is to retrieve and examine it. This is crucial for verifying that your data was stored correctly and for building applications that read from the database. MongoDB provides a powerful find() method for this purpose.
To retrieve all documents in the books collection, use the find() method without any arguments.
db.books.find();
This command will list all four documents currently in your collection. The output can be lengthy, but it's a good way to see everything at once.
More often, you will want to find documents that match specific criteria. To find all books published before 1950, you can use a query filter with the $lt (less than) operator.
db.books.find({ year: { $lt: 1950 } });
This query will return the documents for "The Great Gatsby", "1984", and "Pride and Prejudice".
Sometimes, you only need specific fields from the documents, not the entire document. This is called projection. To retrieve only the title and author of all books in the "Classic" genre, you can add a projection document as the second argument to find().
db.books.find({ genres: "Classic" }, { title: 1, author: 1, _id: 0 });
In the projection document, 1 means "include this field" and 0 means "exclude this field". By default, the _id field is always included, so we explicitly exclude it with _id: 0.
The output will be a clean list of titles and authors:
[
{ "title": "The Great Gatsby", "author": "F. Scott Fitzgerald" },
{ "title": "To Kill a Mockingbird", "author": "Harper Lee" },
{ "title": "Pride and Prejudice", "author": "Jane Austen" }
]
Handle Insert Errors with a Unique Index
Data integrity is vital for any database. One way to enforce it is by preventing duplicate entries. In this step, you will learn how to create a unique index and observe how MongoDB handles attempts to violate this constraint.
Let's ensure that no two books in our collection can have the same title. To do this, create a unique index on the title field.
db.books.createIndex({ title: 1 }, { unique: true });
The output confirms the name of the index that was created.
title_1
Now that the unique index is in place, let's try to insert a document with a title that already exists in the collection, such as "1984".
db.books.insertOne({
title: "1984",
author: "George Orwell",
year: 1949,
genres: ["Dystopian", "Science Fiction"],
stock: 20
});
This operation will fail. MongoDB will throw a MongoBulkWriteException with an error code E11000, which indicates a duplicate key violation. This is the expected behavior and confirms that our unique index is working correctly.
MongoBulkWriteException: E11000 duplicate key error collection: bookstore.books index: title_1 dup key: { title: "1984" }
In an application, you would wrap such database operations in a try...catch block to handle these errors gracefully instead of crashing the program. You can simulate this in the mongosh shell as well.
try {
db.books.insertOne({
title: "1984",
author: "George Orwell"
});
} catch (e) {
print("Error inserting document:", e.message);
}
This command will catch the exception and print a user-friendly error message, demonstrating a robust way to handle potential insertion failures.
Enforce Data Integrity with Schema Validation
While MongoDB is known for its flexible schema, you can enforce a specific structure for your documents using schema validation. This ensures that all documents in a collection adhere to a defined set of rules, improving data quality and consistency.
In this final step, you will add a validator to the books collection. This validator will require every document to have a title, author, and year, and it will enforce specific data types and ranges for these fields.
Use the collMod (modify collection) command to add the validator.
db.runCommand({
collMod: "books",
validator: {
$jsonSchema: {
bsonType: "object",
required: ["title", "author", "year"],
properties: {
title: {
bsonType: "string",
description: "must be a string and is required"
},
author: {
bsonType: "string",
description: "must be a string and is required"
},
year: {
bsonType: "int",
minimum: 1000,
maximum: 2024,
description: "must be an integer between 1000 and 2024"
}
}
}
}
});
The output { ok: 1 } confirms that the validator was successfully applied.
Now, let's test the validator by attempting to insert a document that violates the rules. This document has a year that is out of the allowed range.
db.books.insertOne({
title: "The Hobbit",
author: "J.R.R. Tolkien",
year: 999
});
The insertion will fail, and MongoDB will return an error message explaining that the document failed validation.
MongoBulkWriteException: Document failed validation
This confirms that your schema validation rule is active and effectively protecting the integrity of your data. This powerful feature combines the flexibility of a NoSQL database with the reliability of data validation.
Summary
In this lab, you have successfully learned the core techniques for inserting data into a MongoDB collection. You began by inserting a single document with insertOne() and then efficiently added multiple documents using the insertMany() bulk operation.
You also practiced how to query and verify your data using find() and countDocuments(). Most importantly, you explored two key methods for ensuring data integrity: creating a unique index to prevent duplicates and implementing schema validation to enforce a consistent document structure. These skills are fundamental for building robust and reliable applications with MongoDB.

