Understanding MongoDB Structure
What is MongoDB? MongoDB is a database — a place to store and organize information. It's a digital filing cabinet where you can keep all your data organized and easy to find.
To understand MongoDB, consider a library with books:
| Library Concept | MongoDB Concept | MySQL Equivalent |
|---|---|---|
| The library building | Your computer | Server / Host |
| The card catalog system | MongoDB | MySQL (DBMS) |
| Each section (fiction, science, history) | A database | DATABASE |
| Each shelf in a section | A collection | TABLE |
| Each book on a shelf | A document | ROW / Record |
Key Concepts: Database, Collection & Document
Before we start, let's understand the basic building blocks of MongoDB.
1. Database
What is a database? A container that holds related information. Think of a drawer in a filing cabinet — one drawer for "Sales", another for "Customers".
In MongoDB: You can have multiple databases on your computer, each serving a different purpose.
2. Collection
What is a collection? A group of similar documents stored together. In a drawer labeled "Sales", you might have folders for "2023 Sales", "2024 Sales", etc.
In MongoDB: Collections are like tables in traditional databases, but more flexible.
3. Document
What is a document? A single record containing information in a structured format. Consider a single piece of paper in your folder with fields like Customer name, Purchase date, Amount, and Items.
In MongoDB: Documents are like rows in traditional databases, but they can have different structures.
4. JSON / BSON
What is JSON? JSON (JavaScript Object Notation) is a way to organize information that humans and computers can understand.
BSON is MongoDB's internal format — similar to JSON but optimized for storage and speed.
Explore the Sample Supplies Dataset
We'll work with the Sample Supplies dataset — a collection of 5000 sales transactions from a retail store.
What does the data look like?
{
"_id": ObjectId("..."),
"saleDate": ISODate("2024-01-15"),
"items": [
{
"name": "Pen",
"tags": ["office", "writing"],
"price": Decimal128("2.50"),
"quantity": 3
}
],
"storeLocation": "Denver",
"customer": {
"age": 35,
"email": "john@example.com",
"gender": "M",
"satisfaction": 4
},
"couponUsed": false,
"purchaseMethod": "In-store"
}
Understanding the Fields
| Field | What it means | Example |
|---|---|---|
| _id | Unique ID for each sale | Like a receipt number |
| saleDate | When the sale happened | The date stamped on receipt |
| items | List of things bought | The items listed on receipt |
| storeLocation | Which store branch | The store address on receipt |
| customer | Info about who bought | Customer details on loyalty card |
| couponUsed | Whether discount was applied | "coupon: yes/no" on receipt |
| purchaseMethod | How they paid | "payment: cash/card" on receipt |
countDocuments() returns the total number of sales records in
the dataset.
Connect to the MongoDB Shell
docker exec -it mongodb mongosh
// Switch to admin database
use admin
// Login with username and password
db.auth("admin", "password")
{ ok: 1 } means "login successful!"
// Switch to sample_supplies database
use sample_supplies
CRUD Operations: Create & Read
Create — Insert a Single Document
db.sales.insertOne({
saleDate: new Date("2024-01-20"),
items: [
{
name: "Laptop",
tags: ["electronics", "computer"],
price: Decimal128("999.99"),
quantity: 1
}
],
storeLocation: "New York",
customer: {
age: 28,
email: "sarah@example.com",
gender: "F",
satisfaction: 5
},
couponUsed: true,
purchaseMethod: "Online"
})
{
acknowledged: true,
insertedId: ObjectId("...")
}
Create — Insert Multiple Documents
db.sales.insertMany([
{
saleDate: new Date("2024-01-21"),
items: [
{ name: "Keyboard", tags: ["electronics"],
price: Decimal128("49.99"), quantity: 2 }
],
storeLocation: "Chicago",
customer: { age: 35, email: "mike@example.com",
gender: "M", satisfaction: 4 },
couponUsed: false,
purchaseMethod: "In-store"
},
{
saleDate: new Date("2024-01-22"),
items: [
{ name: "Mouse", tags: ["electronics"],
price: Decimal128("29.99"), quantity: 1 },
{ name: "Mousepad", tags: ["accessories"],
price: Decimal128("9.99"), quantity: 1 }
],
storeLocation: "Boston",
customer: { age: 42, email: "lisa@example.com",
gender: "F", satisfaction: 5 },
couponUsed: true,
purchaseMethod: "In-store"
}
])
Read — Finding Data
// Get all documents
db.sales.find()
// Get a single document
db.sales.findOne()
// Find all sales from Denver store
db.sales.find({ storeLocation: "Denver" })
// Find first sale from Chicago store
db.sales.findOne({ storeLocation: "Chicago" })
// Count how many sales happened at the Denver store
db.sales.countDocuments({ storeLocation: "Denver" })
CRUD Operations: Update & Delete
Update a Single Document
db.sales.updateOne(
{ storeLocation: "Denver" },
{ $set: { "customer.satisfaction": 5 } }
)
{
acknowledged: true,
matchedCount: 1,
modifiedCount: 1
}
Update Multiple Documents
db.sales.updateMany(
{ storeLocation: "Denver" },
{ $set: { "customer.satisfaction": 4 } }
)
Delete — Removing Data
// Delete a single document
db.sales.deleteOne({ storeLocation: "Denver" })
// Delete multiple documents
db.sales.deleteMany({ storeLocation: "Denver" })
deleteMany()
— it removes all matching documents! Deleted data cannot be recovered
without re-importing the dataset.
Querying Data: Operators, Sorting & Projection
Comparison Operators
| Operator | Meaning | Example |
|---|---|---|
| $eq | Equal to | { field: { $eq: value } }
|
| $ne | Not equal to | { field: { $ne: value } }
|
| $gt | Greater than | { field: { $gt: value } }
|
| $gte | Greater than or equal to | { field: { $gte: value } }
|
| $lt | Less than | { field: { $lt: value } }
|
| $lte | Less than or equal to | { field: { $lte: value } }
|
| $in | Matches any value in list | { field: { $in: [v1, v2] } }
|
| $nin | Matches none of values | { field: { $nin: [v1, v2] } }
|
// Find sales with satisfaction rating greater than 3
db.sales.find({ "customer.satisfaction": { $gt: 3 } })
// Count sales with satisfaction rating greater than 3
db.sales.countDocuments({ "customer.satisfaction": { $gt: 3 } })
// Find sales from Denver OR Chicago
db.sales.find({ storeLocation: { $in: ["Denver", "Chicago"] } })
// Find sales NOT from Denver
db.sales.find({ storeLocation: { $ne: "Denver" } })
Logical Operators
| Operator | Meaning | Example |
|---|---|---|
| $and | All conditions must be true | { $and: [c1, c2] }
|
| $or | At least one condition true | { $or: [c1, c2] }
|
| $not | Condition must be false | { $not: { field: value } }
|
| $nor | None of conditions true | { $nor: [c1, c2] }
|
// Find sales from Denver AND with satisfaction > 3
db.sales.find({
$and: [
{ storeLocation: "Denver" },
{ "customer.satisfaction": { $gt: 3 } }
]
})
// Find sales from Denver OR with coupon used
db.sales.find({
$or: [
{ storeLocation: "Denver" },
{ couponUsed: true }
]
})
Sorting Results
// Sort by satisfaction rating (lowest first)
db.sales.find().sort({ "customer.satisfaction": 1 })
// Sort by satisfaction rating (highest first)
db.sales.find().sort({ "customer.satisfaction": -1 })
// Sort by store location, then by satisfaction
db.sales.find().sort({
storeLocation: 1,
"customer.satisfaction": -1
})
1 = Ascending (A→Z, 1→10)
| -1 = Descending (Z→A, 10→1)
Limiting Results (Pagination)
// Get only the first 5 sales
db.sales.find().limit(5)
// Skip the first 10 sales, then get the next 5
db.sales.find().skip(10).limit(5)
// Get sales 11-20 (page 2 if showing 10 per page)
db.sales.find().skip(10).limit(10)
Selecting Specific Fields (Projection)
// Show only storeLocation and saleDate, exclude _id
db.sales.find(
{},
{ storeLocation: 1, saleDate: 1, _id: 0 }
)
1 = Show this field
| 0 = Hide this field. _id is shown by default; to hide it, set _id: 0.
Aggregation Pipelines
What is aggregation? Aggregation is creating summary tables from raw data — like creating pivot tables in Excel where you group data and calculate totals, averages, etc.
The process works like an assembly line in a factory:
- Raw data comes in
- Step 1 processes it
- Step 2 processes the result
- Step 3 processes that result
- Final result comes out
1. $match Stage (Filtering)
// Only count sales from Denver
db.sales.aggregate([
{ $match: { storeLocation: "Denver" } }
])
2. $group Stage (Grouping & Calculating)
// Count sales by store location
db.sales.aggregate([
{
$group: {
_id: "$storeLocation",
totalSales: { $sum: 1 }
}
}
])
_id: "$storeLocation" — Group by the storeLocation
field. totalSales: { $sum: 1 } — Count each
document as 1.
3. Combining Stages
// Count sales from Denver only
db.sales.aggregate([
{ $match: { storeLocation: "Denver" } },
{
$group: {
_id: "$storeLocation",
totalSales: { $sum: 1 }
}
}
])
Common Calculations
| Calculation | What it does | Description |
|---|---|---|
| $sum | Adds up values | Calculates total sales |
| $avg | Calculates average | Finds average sale amount |
| $min | Finds smallest value | Identifies cheapest item |
| $max | Finds largest value | Identifies most expensive item |
| $count | Counts documents | Counts how many sales occurred |
// Calculate average satisfaction by store
db.sales.aggregate([
{
$group: {
_id: "$storeLocation",
averageSatisfaction: { $avg: "$customer.satisfaction" }
}
}
])
// Find the highest and lowest satisfaction ratings
db.sales.aggregate([
{
$group: {
_id: "$storeLocation",
maxSatisfaction: { $max: "$customer.satisfaction" },
minSatisfaction: { $min: "$customer.satisfaction" }
}
}
])
Practice Exercises
Try these exercises to test your understanding. Each exercise builds on the previous ones.
Exercise 1: Basic Queries
Task: Find all sales from the "Seattle" store.
Exercise 2: Filtering
Task: Find all sales where the customer satisfaction is 5 (very satisfied).
Exercise 3: Multiple Conditions
Task: Find all sales from "Denver" where the customer used a coupon.
Exercise 4: Sorting
Task: Find the 5 most recent sales from "Chicago".
Exercise 5: Projection
Task: Show only the store location and sale date for sales from "New York".
Exercise 6: Aggregation
Task: Count how many sales occurred at each store location.
Exercise 7: Advanced Aggregation
Task: Calculate the average customer satisfaction for each store location, sorted by highest satisfaction first.
Tutorial Verification Checklist
Run these integrity checks in your MongoDB shell to confirm you're ready for the next tutorial.
docker exec -it mongodb mongosh
Opens the interactive mongosh prompt
use admin; db.auth("admin", "password")
Returns { ok: 1 }
db.sales.countDocuments()
Returns 28554 documents
db.sales.aggregate([{ $group: { _id: "$storeLocation", n: { $sum: 1 } } }])
Returns one document per store location
Troubleshooting Common Issues
Quick Reference Commands
Bookmark these everyday commands for future lab assignments.
docker exec -it mongodb mongosh
use admin
db.auth("admin", "password")
use sample_supplies
// Find
db.collection.find({ filter })
db.collection.findOne({ filter })
// Insert
db.collection.insertOne({ document })
db.collection.insertMany([{ doc1 }, { doc2 }])
// Update
db.collection.updateOne(
{ filter }, { $set: { field: value } }
)
db.collection.updateMany(
{ filter }, { $set: { field: value } }
)
// Delete
db.collection.deleteOne({ filter })
db.collection.deleteMany({ filter })
// Aggregation
db.collection.aggregate([
{ $match: { filter } },
{ $group: {
_id: "$field",
calculation: { $operator: "$field" }
} }
])