MongoDB Lab Series: Fundamentals

Tutorial 02

MongoDB Fundamentals for Big Data Analysis

Master CRUD operations, querying, and aggregation pipelines to analyze the Sample Supplies dataset (5000 records). Everything you write runs inside the MongoDB shell from Tutorial 1.

Before You Start

Complete Tutorial 1: Environment Setup — your MongoDB container must be running.

Suggested time: 60-90 minutes

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
MongoDB is special because it's "NoSQL" — it doesn't require rigid tables like traditional databases. Instead, it's flexible, allowing you to add any type of information you want.

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?

sample_supplies.sales — Document Structure json
{
  "_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
Expected result: The raw JSON documents appear, and countDocuments() returns the total number of sales records in the dataset.

Connect to the MongoDB Shell

1. Open a shell inside the running container:
Terminal — Connect to MongoDB Shell bash
docker exec -it mongodb mongosh
2. Authenticate with the admin credentials from Tutorial 1:
MongoDB Shell — Authenticate javascript
// Switch to admin database
use admin

// Login with username and password
db.auth("admin", "password")
Expected output: { ok: 1 } means "login successful!"
3. Switch to our target database:
MongoDB Shell — Select Database javascript
// Switch to sample_supplies database
use sample_supplies

CRUD Operations: Create & Read

CRUD stands for Create, Read, Update, Delete — the four basic things you can do with data.

Create — Insert a Single Document

MongoDB Shell — insertOne javascript
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"
})
Expected output:
{
  acknowledged: true,
  insertedId: ObjectId("...")
}

Create — Insert Multiple Documents

MongoDB Shell — insertMany javascript
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

MongoDB Shell — find / findOne javascript
// 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

MongoDB Shell — updateOne javascript
db.sales.updateOne(
  { storeLocation: "Denver" },
  { $set: { "customer.satisfaction": 5 } }
)
Expected output:
{
  acknowledged: true,
  matchedCount: 1,
  modifiedCount: 1
}

Update Multiple Documents

MongoDB Shell — updateMany javascript
db.sales.updateMany(
  { storeLocation: "Denver" },
  { $set: { "customer.satisfaction": 4 } }
)

Delete — Removing Data

MongoDB Shell — deleteOne / deleteMany javascript
// Delete a single document
db.sales.deleteOne({ storeLocation: "Denver" })

// Delete multiple documents
db.sales.deleteMany({ storeLocation: "Denver" })
Warning: Be careful with 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] } }
MongoDB Shell — Comparison Operator Examples javascript
// 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] }
MongoDB Shell — Logical Operator Examples javascript
// 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

MongoDB Shell — sort() javascript
// 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
})
Numbers: 1 = Ascending (A→Z, 1→10)  |  -1 = Descending (Z→A, 10→1)

Limiting Results (Pagination)

MongoDB Shell — limit() / skip() javascript
// 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)
Why useful? This is called pagination — showing results in pages, like in web searches.

Selecting Specific Fields (Projection)

MongoDB Shell — Projection javascript
// Show only storeLocation and saleDate, exclude _id
db.sales.find(
  {},
  { storeLocation: 1, saleDate: 1, _id: 0 }
)
Numbers: 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.

Historical Note: MongoDB previously used MapReduce for aggregation tasks. MapReduce has been deprecated since MongoDB 5.0 and replaced with Aggregation Pipelines, which are more efficient and easier to use. This tutorial focuses on the modern Aggregation Pipeline approach.

The process works like an assembly line in a factory:

  1. Raw data comes in
  2. Step 1 processes it
  3. Step 2 processes the result
  4. Step 3 processes that result
  5. Final result comes out

1. $match Stage (Filtering)

MongoDB Shell — $match Stage javascript
// Only count sales from Denver
db.sales.aggregate([
  { $match: { storeLocation: "Denver" } }
])

2. $group Stage (Grouping & Calculating)

MongoDB Shell — $group Stage javascript
// Count sales by store location
db.sales.aggregate([
  {
    $group: {
      _id: "$storeLocation",
      totalSales: { $sum: 1 }
    }
  }
])
What this means: _id: "$storeLocation" — Group by the storeLocation field. totalSales: { $sum: 1 } — Count each document as 1.

3. Combining Stages

MongoDB Shell — $match + $group javascript
// 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
MongoDB Shell — Aggregation Examples javascript
// 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.

Congratulations! You've learned the MongoDB fundamentals: key concepts, CRUD operations, querying, and aggregation. Proceed to the Tutorial 3: Advanced MongoDB for real-world big data.

Tutorial Verification Checklist

Run these integrity checks in your MongoDB shell to confirm you're ready for the next tutorial.

1. Shell Access docker exec -it mongodb mongosh

Opens the interactive mongosh prompt

2. Authentication use admin; db.auth("admin", "password")

Returns { ok: 1 }

3. Dataset Presence db.sales.countDocuments()

Returns 28554 documents

4. Aggregation Sanity 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.

Connecting to MongoDB bash
docker exec -it mongodb mongosh
use admin
db.auth("admin", "password")
use sample_supplies
Basic CRUD & Aggregation Reference javascript
// 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" }
  } }
])