Introduction
In this lab, you will learn the fundamentals of designing a structured document schema for product data using MongoDB. For an e-commerce application, a well-designed schema is crucial for performance and scalability. You will start by creating a simple product document and progressively enhance it by embedding related data like pricing and stock information, and by using arrays for multi-value attributes. By the end of this lab, you will have a solid understanding of how to model product data effectively in a MongoDB database.
Create a Basic Product Document
In this first step, you will connect to the MongoDB server, create a new database, and insert your first product document. This will establish the foundation of our product catalog.
First, open the MongoDB Shell (mongosh) to interact with the database from your terminal.
mongosh
You will see a prompt like test> indicating you are connected to the MongoDB server. Now, let's create and switch to a new database named product_catalog. In MongoDB, a database is created automatically when you first store data in it.
use product_catalog
The output switched to db product_catalog confirms that you are now working within this new database.
Next, we will create a collection called products and insert a single document into it. A document in MongoDB is a BSON object, which is represented like JSON. We will use the insertOne() method.
db.products.insertOne({
name: "Wireless Headphones",
brand: "SoundWave",
category: "Electronics",
sku: "SW-HD-001"
});
This command inserts a document with four fields: name, brand, category, and sku. The output will show an acknowledgment and the unique _id assigned to the document by MongoDB.
{
"acknowledged": true,
"insertedId": ObjectId("...")
}
To verify that the document was created successfully, you can use the find() method to retrieve all documents from the products collection.
db.products.find();
The output will display the document you just inserted, including its automatically generated _id.
[
{
_id: ObjectId('...'),
name: 'Wireless Headphones',
brand: 'SoundWave',
category: 'Electronics',
sku: 'SW-HD-001'
}
]
You have now successfully created your first product document. We will continue working within the mongosh shell for the next steps.
Embed Price and Stock Information
A key advantage of MongoDB's document model is the ability to embed related information within a single document. In this step, you will update the existing product to include nested objects for pricing and stock details. This approach keeps all relevant product data together, which can improve query performance by reducing the need for separate lookups.
We will use the updateOne() method to modify the document we created. This method takes two arguments: a filter to identify the document to update, and an update operator that specifies the changes.
Let's add a price object and a stock object. We'll use the $set operator to add these new fields.
db.products.updateOne(
{ sku: "SW-HD-001" },
{
$set: {
price: {
base: 149.99,
currency: "USD"
},
stock: {
quantity: 250,
inStock: true
}
}
}
);
Let's break down this command:
- The first object
{ sku: "SW-HD-001" }is the filter. It tells MongoDB to find the document where theskufield is "SW-HD-001". - The second object
{ $set: { ... } }is the update operation.$setadds new fields or modifies existing ones. Here, we are adding thepriceandstockfields, which are themselves embedded documents.
The output will confirm that one document was matched and modified.
{
"acknowledged": true,
"insertedId": null,
"matchedCount": 1,
"modifiedCount": 1,
"upsertedCount": 0
}
Now, let's retrieve the document again to see the changes.
db.products.find({ sku: "SW-HD-001" });
The output now shows the product with the newly embedded price and stock information. This structure is more organized and intuitive than having separate tables for price and stock in a relational database.
[
{
_id: ObjectId('...'),
name: 'Wireless Headphones',
brand: 'SoundWave',
category: 'Electronics',
sku: 'SW-HD-001',
price: { base: 149.99, currency: 'USD' },
stock: { quantity: 250, inStock: true }
}
]
Use Arrays for Product Attributes
Products often have attributes that can have multiple values, such as available colors, tags for searching, or a list of specifications. MongoDB handles this elegantly with arrays. In this step, you will add an array of tags to your product document.
We will again use the updateOne() method with the $set operator to add a new field called tags. This field will contain an array of strings.
db.products.updateOne(
{ sku: "SW-HD-001" },
{
$set: {
tags: ["audio", "wireless", "over-ear", "noise-canceling"]
}
}
);
This command finds the product with sku: "SW-HD-001" and adds a tags array to it. The output will again confirm that one document was modified.
To see the result, query for the document once more.
db.products.find({ sku: "SW-HD-001" });
The updated document now includes the tags array. Storing these values in an array makes it easy to query for products that have a specific tag.
[
{
_id: ObjectId('...'),
name: 'Wireless Headphones',
brand: 'SoundWave',
category: 'Electronics',
sku: 'SW-HD-001',
price: { base: 149.99, currency: 'USD' },
stock: { quantity: 250, inStock: true },
tags: [ 'audio', 'wireless', 'over-ear', 'noise-canceling' ]
}
]
Arrays are a powerful feature for modeling one-to-many relationships and storing lists of related data directly within a document.
Add and Query Multiple Products
A product catalog will contain many items. In this step, you will learn how to add multiple products at once and then perform a basic query to filter them.
To add multiple documents to a collection simultaneously, you can use the insertMany() method. This method takes an array of documents as its argument. Let's add two new products to our products collection.
db.products.insertMany([
{
name: "Smartwatch",
brand: "FitTech",
category: "Electronics",
sku: "FT-SW-005",
price: { base: 199.99, currency: "USD" },
stock: { quantity: 150, inStock: true },
tags: ["wearable", "fitness", "smartwatch"]
},
{
name: "Classic T-Shirt",
brand: "UrbanWear",
category: "Apparel",
sku: "UW-TS-001",
price: { base: 24.99, currency: "USD" },
stock: { quantity: 500, inStock: true },
tags: ["clothing", "cotton", "casual"]
}
]);
The output will acknowledge the operation and list the _id values for the two newly inserted documents.
Now that we have multiple products, let's perform a query to find only the products that belong to the "Electronics" category. You can do this by passing a filter object to the find() method.
db.products.find({ category: "Electronics" });
This command searches the products collection and returns only the documents where the category field has the value "Electronics".
The output will show the two electronic products in our catalog: the "Wireless Headphones" and the "Smartwatch".
[
{
_id: ObjectId('...'),
name: 'Wireless Headphones',
brand: 'SoundWave',
category: 'Electronics',
sku: 'SW-HD-001',
price: { base: 149.99, currency: 'USD' },
stock: { quantity: 250, inStock: true },
tags: [ 'audio', 'wireless', 'over-ear', 'noise-canceling' ]
},
{
_id: ObjectId('...'),
name: 'Smartwatch',
brand: 'FitTech',
category: 'Electronics',
sku: 'FT-SW-005',
price: { base: 199.99, currency: 'USD' },
stock: { quantity: 150, inStock: true },
tags: [ 'wearable', 'fitness', 'smartwatch' ]
}
]
You have now practiced the basic operations for managing a product catalog. You can exit the MongoDB shell.
exit;
Summary
In this lab, you have learned the fundamental principles of structuring product data in MongoDB. You started by creating a database and inserting a basic product document. You then enhanced this document by embedding related data, such as price and stock information, into nested objects. You also learned how to use arrays to handle attributes with multiple values, like product tags. Finally, you practiced adding multiple documents to a collection and performing a basic query to filter data based on a specific field. These skills provide a strong foundation for building flexible and efficient data models for e-commerce applications and other systems using MongoDB.

