Moeein Aali

Introduction to MongoDB


Moeein Aali

Sharif University of Technology
CE384 - Database Design - Spring 2025
Dr. Ramezani

Introduction to MongoDB
Moeein Aali

Agenda


  1. Introduction to MongoDB
    • What is MongoDB?
    • Advantages and Use Cases
  2. Architecture & Key Concepts
    • Document-Based Database
    • Collections and Documents
  3. Installation & Setup with Docker
    • Docker Setup
    • Connecting to MongoDB
  4. MongoDB Shell & Basic Commands
    • Shell Commands
    • CRUD Operations
Introduction to MongoDB
Moeein Aali

What is MongoDB?

MongoDB is a NoSQL database that:

  • Stores data as Documents
  • Uses JSON/BSON format
  • Is Schema-less (flexible)
  • Designed for Big Data and Real-time applications
{
  "_id": "507f1f77bcf86cd799439011",
  "name": "John Doe",
  "age": 25,
  "skills": ["JavaScript", "Python", "MongoDB"]
}
Introduction to MongoDB
Moeein Aali

Meme

center

Introduction to MongoDB
Moeein Aali

MongoDB Advantages

High Performance

  • Fast read and write operations
  • Horizontal scaling capabilities

Flexibility

  • Dynamic schema

Developer Friendly

  • JSON-like syntax

Modern Features

  • Replication
  • Sharding
Introduction to MongoDB
Moeein Aali

SQL vs NoSQL

SQL (Relational) NoSQL (MongoDB)
Tables and Rows Collections and Documents
Fixed Schema Flexible Schema
Complex JOINs Embedded Documents
Full ACID Eventual Consistency
Vertical Scaling Horizontal Scaling
Introduction to MongoDB
Moeein Aali

SQL vs NoSQL

-- SQL
SELECT * FROM users WHERE age > 18;
// MongoDB
db.users.find({ age: { $gt: 18 } })
Introduction to MongoDB
Moeein Aali

Meme

center

Introduction to MongoDB
Moeein Aali

MongoDB Key Concepts

Database

A collection of Collections

Collection

Equivalent to Table in SQL (group of Documents)

Document

Equivalent to Row in SQL (BSON format)

Field

Equivalent to Column in SQL

Introduction to MongoDB
Moeein Aali

MongoDB Key Concepts

Database
  └── Collection (users)
      ├── Document { _id: 1, name: "John" }
      └── Document { _id: 2, name: "Jane", age: 22 }
Introduction to MongoDB
Moeein Aali

Install MongoDB with Docker

docker run --name my-mongo -p 27017:27017 -d docker.arvancloud.ir/mongo:latest
Introduction to MongoDB
Moeein Aali

Connecting to MongoDB

Connect via Shell

docker exec -it my-mongo mongosh

or directly

mongosh mongodb://localhost:27017

Additional Configuration

docker run --name my-mongo \
  -p 27017:27017 \
  -e MONGO_INITDB_ROOT_USERNAME=admin \
  -e MONGO_INITDB_ROOT_PASSWORD=password123 \
  -d docker.arvancloud.ir/mongo:latest
Introduction to MongoDB
Moeein Aali

MongoDB Shell - Basic Commands

Show Databases

show dbs

Create/Select Database

use myDatabase

Show Collections

show collections

Current Database Info

db
db.stats()
Introduction to MongoDB
Moeein Aali

CRUD Operations - Create

insertOne - Insert Single Document

db.users.insertOne({
  name: "John Doe",
  age: 25,
  email: "john@example.com",
  city: "New York"
})

insertMany - Insert Multiple Documents

db.users.insertMany([
  { name: "Jane Smith", age: 22, city: "London" },
  { name: "Bob Johnson", age: 28, city: "Paris" },
  { name: "Alice Brown", age: 24, city: "Tokyo" }
])
Introduction to MongoDB
Moeein Aali

CRUD Operations - Read

find - Find Documents

// All documents
db.users.find()

// With condition
db.users.find({ age: 25 })

// Complex condition
db.users.find({ age: { $gt: 20, $lt: 30 } })

// Find one document
db.users.findOne({ name: "John Doe" })

Select Specific Fields

// Only name and age
db.users.find({}, { name: 1, age: 1, _id: 0 })
Introduction to MongoDB
Moeein Aali

CRUD Operations - Update

updateOne - Update Single Document

db.users.updateOne(
  { name: "John Doe" },
  { $set: { age: 26, email: "newemail@example.com" } }
)

updateMany - Update Multiple Documents

db.users.updateMany(
  { city: "New York" },
  { $set: { country: "USA" } }
)
Introduction to MongoDB
Moeein Aali

CRUD Operations – Update - Useful Operators

// Set a field
db.users.updateOne(
  { name: "John Doe" },
  { $set: { age: 30, city: "Tehran" } }
)
// Increment a number
db.users.updateOne(
  { name: "John Doe" },
  { $inc: { age: 1 } }
)
// Multiply a number
db.users.updateOne(
  { name: "John Doe" },
  { $mul: { salary: 1.1 } }
)
Introduction to MongoDB
Moeein Aali

CRUD Operations – Update - Useful Operators

// Rename a field
db.users.updateOne(
  {},
  { $rename: { "fullname": "name" } }
)
// Unset (remove) a field
db.users.updateOne(
  {},
  { $unset: { tempField: "" } }
)
// Add to array (allow duplicates)
db.users.updateOne(
  {},
  { $push: { skills: "MongoDB" } }
)

Introduction to MongoDB
Moeein Aali

CRUD Operations – Update - Useful Operators

// Add to array (prevent duplicates)
db.users.updateOne(
  {},
  { $addToSet: { skills: "MongoDB" } }
)
// Remove from array
db.users.updateOne(
  {},
  { $pull: { skills: "PHP" } }
)
// Set minimum / maximum value
db.users.updateOne(
  {},
  { $min: { age: 18 }, $max: { age: 65 } }
)
Introduction to MongoDB
Moeein Aali

CRUD Operations - Delete

deleteOne - Delete Single Document

db.users.deleteOne({ name: "John Doe" })

deleteMany - Delete Multiple Documents

// Delete users over 30
db.users.deleteMany({ age: { $gt: 30 } })

// Delete all documents
db.users.deleteMany({})

Drop Entire Collection

db.users.drop()
Introduction to MongoDB
Moeein Aali

Query Operators

Comparison Operators

// Equal
db.users.find({ age: 25 })

// Greater than
db.users.find({ age: { $gt: 20 } })

// Less than or equal
db.users.find({ age: { $lte: 30 } })

// Range
db.users.find({ age: { $gte: 20, $lte: 30 } })

// In array
db.users.find({ city: { $in: ["New York", "London"] } })
Introduction to MongoDB
Moeein Aali

Query Operators - Logical

// OR: Either condition is true
db.users.find({
  $or: [
    { age: { $lt: 20 } },
    { age: { $gt: 30 } }
  ]
})
// AND: Both conditions must be true
db.users.find({
  $and: [
    { age: { $gte: 18 } },
    { city: "Tehran" }
  ]
})

Introduction to MongoDB
Moeein Aali

Query Operators - Logical

// NOT: Negates a condition
db.users.find({
  age: { $not: { $gt: 25 } }
})
// NOR: None of the conditions should be true
db.users.find({
  $nor: [
    { age: { $lt: 20 } },
    { city: "New York" }
  ]
})
// Implicit AND (default behavior)
db.users.find({
  age: { $gte: 18, $lte: 30 },
  city: "Tehran"
})
Introduction to MongoDB
Moeein Aali

Sorting

sort - Sorting

// Ascending
db.users.find().sort({ age: 1 })
// Descending
db.users.find().sort({ age: -1 })
// Multiple fields
db.users.find().sort({ age: -1, name: 1 })
Introduction to MongoDB
Moeein Aali

Limiting

limit and skip

// Only first 5 records
db.users.find().limit(5)
// Skip first 10 records
db.users.find().skip(10)
// Pagination
db.users.find().skip(10).limit(5)
Introduction to MongoDB
Moeein Aali

Practical Exercise 1

Exercise: Bookstore Management

  1. Create a books collection
  2. Insert the following books:
db.books.insertMany([
  {
    title: "The Alchemist",author: "Paulo Coelho",year: 1988,
    price: 15.99,category: "Fiction",inStock: true
  },
  {
    title: "1984",author: "George Orwell", year: 1949,
    price: 12.99,category: "Dystopian",inStock: false
  }
])
Introduction to MongoDB
Moeein Aali

Practical Exercise 1

Questions:

  1. Display all books in stock
  2. Find books under $14
  3. Display fiction books that are in stock
  4. Change "The Alchemist" price to $16.99
  5. Find books published after 1980
Introduction to MongoDB
Moeein Aali

Practical Exercise 1 - Solutions

// 1. All books in stock
db.books.find({ inStock: true })

// 2. Books under $14
db.books.find({ price: { $lt: 14 } })

// 3. Fiction books in stock
db.books.find({ category: "Fiction", inStock: true })

// 4. Update Alchemist price
db.books.updateOne(
  { title: "The Alchemist" },
  { $set: { price: 16.99 } }
)

// 5. Books after 1980
db.books.find({ year: { $gt: 1980 } })
Introduction to MongoDB
Moeein Aali

Indexing and Optimization

Creating Indexes

// Simple index
db.users.createIndex({ email: 1 })
// Compound index
db.users.createIndex({ age: 1, city: 1 })

View Indexes

db.users.getIndexes()
Introduction to MongoDB
Moeein Aali

Aggregation Framework

Pipeline Concept

db.users.aggregate([
  { $match: { age: { $gte: 18 } } },
  { $group: { _id: "$city", count: { $sum: 1 } } },
  { $sort: { count: -1 } }
])

Useful Operations

// Count documents
db.users.aggregate([
  { $group: { _id: null, total: { $sum: 1 } } }
])

// Average age
db.users.aggregate([
  { $group: { _id: null, avgAge: { $avg: "$age" } } }
])
Introduction to MongoDB
Moeein Aali

Practical Exercise 2

Exercise: Sales Analytics

  1. Create an orders collection with this data:
db.orders.insertMany([
  { customer: "John", product: "Laptop", amount: 1200, date: new Date("2024-01-15") },
  { customer: "Jane", product: "Phone", amount: 800, date: new Date("2024-01-20") },
  { customer: "John", product: "Mouse", amount: 25, date: new Date("2024-02-01") },
  { customer: "Bob", product: "Tablet", amount: 400, date: new Date("2024-02-10") }
])
  1. Calculate total sales per customer
  2. Find average order amount
Introduction to MongoDB
Moeein Aali

Practical Exercise 2 - Solution

db.orders.aggregate([
  {
    $group: {
      _id: null,                      // All documents together
      averageAmount: { $avg: "$amount" }  // Calculate average
    }
  }
])
db.orders.aggregate([
  {
    $group: {
      _id: null,                      // All documents together
      averageAmount: { $avg: "$amount" }  // Calculate average
    }
  }
])
Introduction to MongoDB
Moeein Aali

Useful Tools

MongoDB Compass

  • Graphical interface for MongoDB
  • Data visualization and editing
  • Performance analysis

MongoDB Atlas

  • MongoDB as a Service
  • Cloud-based solution
  • Automatic scaling
Introduction to MongoDB
Moeein Aali

The End!

Introduction to MongoDB