Section 5: MongoDB Basics

πŸ“‚ Databases & Collections: The Complete Guide

Master MongoDB's fundamental building blocks with interactive examples, live console, animations, and real-world scenarios - The most comprehensive tutorial on the internet!

πŸ“– Meet Maya - The Digital Library Organizer

Maya manages a massive digital library with 10 million documents - books, magazines, research papers, comics, and newspapers. When she started, she made a critical mistake that almost destroyed everything...

😱

THE CHAOS: Single Folder Disaster

Month 1 - Everything in ONE folder

❌ The Problem:

  • 10 million files in ONE folder - Opening it took 5 minutes! 😱
  • Books mixed with comics, magazines with research papers - Complete chaos!
  • Finding anything? Impossible! Search took 30+ minutes
  • System kept crashing - Files corrupted, data lost
  • No organization by topic, author, or year
  • Backup? The single folder was 2TB - couldn't backup!

Real Crisis: When the library director asked "How many science fiction books do we have?", Maya had to tell them: "I don't know. It will take 2 days to count them." πŸ˜“

πŸŽ‰

THE SOLUTION: MongoDB-Style Organization

Month 2 - Hierarchical Structure

βœ… How Maya Fixed It:

🏒 Level 1: DATABASE = "DigitalLibrary"

The main container for everything

πŸ“‚ Level 2: COLLECTIONS = Categories
  • "books" collection - 5 million book documents πŸ“š
  • "magazines" collection - 2 million magazine documents πŸ“°
  • "research_papers" collection - 1 million papers πŸ“„
  • "comics" collection - 1.5 million comics πŸ“–
  • "newspapers" collection - 500K newspapers πŸ—žοΈ
πŸš€ The Results:
  • βœ… Search time: 30 minutes β†’ 0.2 seconds (100x faster!)
  • βœ… Finding science fiction books: 2 days β†’ INSTANT
  • βœ… No more crashes - Each collection managed independently
  • βœ… Easy backups - Backup each collection separately
  • βœ… Perfect organization - Everything in its proper place

πŸ’‘ This is EXACTLY How MongoDB Works!

❌ Maya's Old Way:
One giant folder
= Slow, Chaotic, Crash-prone

β†’

βœ… MongoDB Way:
Database β†’ Collections
= Fast, Organized, Scalable

Database = Maya's library building 🏒
Collections = Organized sections (books, magazines, etc.) πŸ“š
Documents = Individual items πŸ“„

πŸ—οΈ MongoDB Data Hierarchy Explained

Complete 5-Level Structure

πŸ–₯️ MongoDB Server localhost:27017 πŸ“¦ ecommerce Database 1 πŸ“¦ blog Database 2 πŸ“¦ school Database 3 πŸ“‚ users πŸ“‚ products πŸ“‚ orders πŸ“„ Document (JSON-like) { _id, name, email, age, address, ... } 🏷️ _id: "abc123" 🏷️ name: "John" 🏷️ age: 30 🏷️ email: "[email protected]"
πŸ–₯️ Server

One MongoDB instance

πŸ“¦ Database

Container for collections

πŸ“‚ Collection

Group of documents

πŸ“„ Document

JSON-like record

🏷️ Field

Key-value pair

🎨 Visual Database Structure

Hover over databases to see their collections!

πŸ–₯️

MongoDB Server

localhost:27017

πŸ“¦
ecommerce

2.3 MB β€’ 4 collections

πŸ“¦
blog

1.5 MB β€’ 3 collections

πŸ“¦
school

3.1 MB β€’ 6 collections

πŸ”’
admin

40 KB β€’ System DB

πŸ“¦ What is a Database?

Simple Definition: A database in MongoDB is a container that holds multiple collections. Think of it as a folder on your computer that contains multiple subfolders.

🏒 Real-World Analogy

🏒
Office Building

The entire structure

=
πŸ–₯️
MongoDB Server

Holds everything

🏬
Departments

HR, Finance, Sales

=
πŸ“¦
Databases

Logical separation

πŸ—„οΈ
Filing Cabinets

In each department

=
πŸ“‚
Collections

Groups of documents

πŸ”‘ Key Characteristics

🏒 Logical Separation

Each database is independent, keeping different applications' data completely separate

πŸ“Š Multiple Collections

One database can contain unlimited collections (tables)

πŸ”’ Independent Access

Each database can have its own users and permissions

πŸ’Ύ Separate Storage

Gets its own files on disk for optimal performance

πŸ“‹ Default System Databases

When you install MongoDB, it comes with 3 default databases. Never delete these!

Database Purpose Size Can Delete?
admin Administrative database for user authentication & authorization ~40 KB ❌ No
local Stores data specific to a single server (not replicated) Varies ❌ No
config Stores sharding configuration for sharded clusters Small ❌ No
⚠️ Important Warning

Don't delete or modify these default databases unless you know exactly what you're doing! They're used by MongoDB internally for critical functions.

πŸ“‚ What is a Collection?

Simple Definition: A collection in MongoDB is a group of documents. It's similar to a table in SQL databases, but with much more flexibility!

πŸ”„ MongoDB vs SQL: The Translation

🐬

SQL World

Database: myshop
Table: customers
Row: Single customer record
Column: name, email, age
CREATE TABLE customers (
  id INT,
  name VARCHAR(50),
  email VARCHAR(100)
);
⟺
πŸƒ

MongoDB World

Database: myshop
Collection: customers
Document: Single customer record
Field: name, email, age
// No schema needed!
db.customers.insertOne({
  name: "John",
  email: "john@email.com"
})

βš–οΈ Key Differences

Feature SQL Table MongoDB Collection
Schema Strict - Must define columns first Flexible - No schema required
Data Structure Rows & Columns (2D table) JSON-like Documents
Adding Fields ALTER TABLE required Just add to new documents
Nested Data Need separate tables + JOINs Store directly in document
Empty Values NULL in every row Simply omit the field

🎯 Collection Characteristics

πŸ”“ Schema-less Freedom

Each document can have different fields. Perfect for evolving applications!

// Valid!
{name: "John", age: 25}
{name: "Sarah", city: "NY"}
πŸ“¦ Embedded Documents

Store related data together instead of spreading across tables

{
  name: "John",
  address: {city: "NY"}
}
πŸ“Š Arrays Support

Store multiple values in a single field without separate tables

{
  name: "Store",
  tags: ["sale", "new"]
}
πŸš€ Dynamic Growth

Add new fields anytime without affecting existing documents

// Old doc: {name}
// New doc: {name, email}
Both valid! βœ“

πŸ’‘ Real-World Example: E-commerce Store

πŸ‘₯
users
Customer accounts
πŸ“¦
products
Items for sale
πŸ›’
orders
Purchase records
⭐
reviews
Customer feedback

Each collection stores related documents. All belong to the ecommerce database

πŸ§ͺ Database Operations Lab

HANDS-ON

Let's learn database operations by actually running them! Try each command in the live console below. πŸš€

OPERATION 1

πŸ“‹ List All Databases

See what databases exist on your MongoDB server

πŸ“ Command:

// Shows all databases with their size
show dbs

βœ… Expected Output:

admin 40KB
config 72KB
local 80KB
myshop 2.3MB
blog 1.5MB

Note: Size is displayed in KB (Kilobytes) or MB (Megabytes)

OPERATION 2

✨ Create / Switch Database

MongoDB creates databases on-the-fly when you use them!

πŸ“ Command:

// Switch to (or create) 'school' database
use school

βœ… Expected Output:

switched to db school
πŸ’‘ Important Concept:

The database isn't actually created until you insert data into it! Try show dbs now - you won't see 'school' yet!

OPERATION 3

πŸ“ Check Current Database

Which database are you currently using?

πŸ“ Command:

// Shows the current database name
db

βœ… Expected Output:

school

Tip: db is a variable that always points to your current database

OPERATION 4

πŸ“Š Database Statistics

Get detailed information about a database

πŸ“ Command:

// Get stats for current database
db.stats()

βœ… Expected Output:

{
  "db": "school",
  "collections": 3,
  "views": 0,
  "objects": 1250,
  "avgObjSize": 456,
  "dataSize": 570000,
  "storageSize": 1048576,
  "indexes": 3,
  "indexSize": 98304
}
Collections
3
Number of collections
Objects
1,250
Total documents
Data Size
557 KB
Actual data size
⚠️ OPERATION 5

πŸ—‘οΈ Delete Database (DANGER!)

⚠️ WARNING: This permanently deletes the database and ALL its data!

πŸ“ Command:

// ⚠️ BE VERY CAREFUL!
use testdb
db.dropDatabase()

βœ… Expected Output:

{
  "ok": 1,
  "dropped": "testdb"
}
🚨 Safety Rules:
  • Never drop production databases!
  • Always backup before dropping
  • Double-check you're on the right database
  • There's NO undo button!

πŸ“š Quick Reference Table

Command What It Does Example
show dbs List all databases show dbs
use [name] Switch/create database use myshop
db Show current database db
db.stats() Get database statistics db.stats()
db.dropDatabase() Delete current database db.dropDatabase()

πŸ’» Live MongoDB Console

Try all commands here! Results appear instantly.

● LIVE
MongoDB Shell
πŸ“ INPUT PANEL
βœ… OUTPUT PANEL
// Output will appear here... πŸ‘‡ Ready to execute commands! Type your MongoDB queries and click RUN.
πŸ’‘ Tip #1
You can write multiple commands - each on a new line!
⚑ Tip #2
Try the example buttons to load pre-written commands!
🎯 Tip #3
This is a simulated console - perfect for learning!

πŸ› οΈ Collection Operations

CRUD OPERATIONS

Collections hold your documents. Learn how to create, read, update, and delete them!

1️⃣ Create Collection

MongoDB creates collections automatically when you insert the first document, but you can create them explicitly too.

πŸ“ Method 1: Automatic Creation (Recommended)

// Just insert a document - collection is created automatically!
db.students.insertOne({
  name: "John Doe",
  age: 20,
  grade: "A"
})

πŸ“ Method 2: Explicit Creation

// Create empty collection
db.createCollection("students")
// With options
db.createCollection("students", {
  capped: true,
  size: 5242880, // 5MB
  max: 5000 // Max documents
})

2️⃣ List All Collections

See all collections in the current database

// Simple way
show collections
// Programmatic way
db.getCollectionNames()
Output Example:
students
teachers
courses
grades

3️⃣ Collection Statistics

Get detailed information about a collection

// Get stats for 'students' collection
db.students.stats()
Key Information Returned:
Document Count
Total documents
Storage Size
Disk space used
Index Count
Number of indexes
Avg Doc Size
Average size

4️⃣ Rename Collection

Change a collection's name

// Rename 'students' to 'pupils'
db.students.renameCollection("pupils")
⚠️ Warning:
If target name already exists, it will be dropped! Use dropTarget: false to prevent this.

5️⃣ Drop (Delete) Collection

⚠️ DANGER ZONE: This permanently deletes all documents!

// ⚠️ Deletes collection and ALL its documents!
db.students.drop()
🚨 Safety Checklist:
  • βœ“ Backup your data first
  • βœ“ Verify you're on the correct database
  • βœ“ Double-check the collection name
  • βœ“ Remember: NO UNDO!

πŸ“š Collection Operations Quick Reference

Operation Command Example
Create (Auto) insertOne/Many db.users.insertOne({...})
Create (Explicit) createCollection db.createCollection("users")
List All show collections show collections
Get Stats .stats() db.users.stats()
Rename .renameCollection db.users.renameCollection("customers")
Delete .drop() db.users.drop()

🌍 Real-World Database Examples

Let's see how real applications structure their MongoDB databases!

πŸ›’

E-Commerce Platform (Amazon, Flipkart style)

Database: ecommerce

πŸ‘₯

users

{
  _id,
  name,
  email,
  password,
  address: [],
  wishlist: [],
  createdAt
}
πŸ“¦

products

{
  _id,
  name,
  description,
  price,
  category,
  stock,
  images: [],
  rating
}
πŸ›οΈ

orders

{
  _id,
  userId,
  items: [],
  total,
  status,
  shipping: {},
  payment: {},
  orderDate
}
⭐

reviews

{
  _id,
  productId,
  userId,
  rating,
  comment,
  helpful,
  createdAt
}
🏫

School Management System

Database: school

πŸ‘¨β€πŸŽ“

students

{
  _id,
  rollNo,
  name,
  class,
  section,
  dob,
  parents: {},
  attendance: []
}
πŸ‘¨β€πŸ«

teachers

{
  _id,
  employeeId,
  name,
  subject,
  classes: [],
  qualification,
  joinDate
}
πŸ“š

courses

{
  _id,
  code,
  name,
  class,
  teacherId,
  credits,
  syllabus: []
}
πŸ“Š

grades

{
  _id,
  studentId,
  courseId,
  marks,
  grade,
  semester,
  year
}
πŸ“

Blog Platform (Medium, Dev.to style)

Database: blog

πŸ“„

posts

{
  _id,
  title,
  slug,
  content,
  authorId,
  tags: [],
  views,
  likes: [],
  published,
  createdAt
}
πŸ’¬

comments

{
  _id,
  postId,
  userId,
  comment,
  parentId,
  likes: [],
  createdAt
}
✍️

users (authors)

{
  _id,
  username,
  email,
  bio,
  avatar,
  followers: [],
  following: [],
  joinedAt
}

πŸ“› Naming Conventions & Rules

Follow these rules for clean, professional database and collection names!

βœ…

Use Lowercase

βœ“ Good:
users, products, order_items
βœ— Bad:
Users, PRODUCTS, OrderItems
πŸ“

Plural for Collections

βœ“ Good:
students, books, categories
βœ— Bad:
student, book, category
Why? A collection holds multiple documents, so plural makes sense!
πŸ”—

Use Underscores

βœ“ Good:
user_profiles, order_items
βœ— Bad:
user-profiles, userProfiles
🚫

Avoid Special Chars

βœ“ Good:
user_data, app_logs
βœ— Bad:
user@data, app-logs!, #users
πŸ“

Keep It Short

βœ“ Good:
orders, user_prefs
βœ— Bad:
customer_order_items_with_details
πŸ’‘

Be Descriptive

βœ“ Good:
user_sessions, product_reviews
βœ— Bad:
data, items, stuff

🚨 Reserved Names - DON'T USE!

These database names are reserved by MongoDB:

admin
local
config
system.*

πŸ“‹ Real-World Naming Examples

Use Case Database Name Collection Names
E-commerce ecommerce users, products, orders, reviews
Social Media social_app users, posts, comments, likes, followers
School school_mgmt students, teachers, courses, grades
Blog blog posts, authors, comments, categories, tags
Task Manager task_app users, projects, tasks, teams

⭐ Best Practices

Follow these pro tips to build better MongoDB applications!

1️⃣

One Database Per Application

Don't mix different applications in one database. Each app should have its own database for better organization and security.

βœ“ Good Example:
πŸ“¦ ecommerce β†’ Shop app
πŸ“¦ blog β†’ Blog app
πŸ“¦ analytics β†’ Analytics service
2️⃣

Design Schema for Your Queries

Structure your collections based on how you'll query them, not based on relational database thinking.

πŸ’‘ Example:
// If you always need user + orders together:
{
  user: {...},
  orders: [...] // Embed directly!
}
3️⃣

Use Indexes Wisely

Create indexes on fields you frequently query. But don't over-index - each index costs storage and slows writes.

// Create index on email for fast lookups
db.users.createIndex({ email: 1 })
// Compound index for common queries
db.orders.createIndex({ userId: 1, date: -1 })
4️⃣

Embed vs Reference

Embed data that you always need together. Reference data that's shared or changes independently.

βœ“ Embed When:
  • One-to-few relationship
  • Data doesn't change often
  • Need data together always
β†’ Reference When:
  • Many-to-many relationship
  • Data shared across docs
  • Large, frequently updated
5️⃣

Use Connection Pooling

Don't create a new connection for every request. Use connection pooling to reuse connections efficiently.

// βœ— Bad: New connection each time
const client = await MongoClient.connect(uri)
// βœ“ Good: Reuse connection pool
const client = new MongoClient(uri, {
  maxPoolSize: 50
})
6️⃣

Always Use Schema Validation (Optional)

While MongoDB is schema-less, you can add validation rules to ensure data quality.

// Add validation rules
db.createCollection("users", {
  validator: {
    $jsonSchema: {
      required: ["name", "email"],
      properties: {
        email: { bsonType: "string" }
      }
    }
  }
})

🚫 Common Mistakes to Avoid

Learn from others' mistakes and save yourself hours of debugging!

❌

Treating MongoDB Like SQL

Don't create separate collections for everything and JOIN them later. Embed related data!

βœ— SQL Thinking:
users β†’ user_addresses
users β†’ user_phones
(Need 3 JOINs!)
βœ“ MongoDB Way:
{
  addresses: [],
  phones: []
}
❌

Not Using Indexes

Queries become slow as data grows. Always index frequently queried fields!

// Slow: Scans all documents
db.users.find({ email: "user@email.com" })
// Fast: Uses index
db.users.createIndex({ email: 1 })
db.users.find({ email: "user@email.com" })
❌

Huge Documents (>16MB)

MongoDB has a 16MB document size limit. Don't store massive arrays in one document!

βœ— Bad: Unlimited growth
{
  user: "john",
  messages: [ ...1000000 items ] // Too big!
}
βœ“ Good: Separate collection
users: { _id, name }
messages: { userId, message }
❌

No Error Handling

Always wrap database operations in try-catch blocks!

// βœ“ Good: Handle errors
try {
  await db.users.insertOne(user)
} catch (error) {
  console.error("Failed:", error)
}
❌

Selecting All Fields

Don't fetch entire documents when you only need a few fields. Use projection!

// βœ— Bad: Returns everything
db.users.find({})
// βœ“ Good: Only what you need
db.users.find({}, { name: 1, email: 1 })

πŸ’Ό Top Interview Questions

MUST KNOW

Master these questions to ace your MongoDB interview! πŸš€

QUESTION 1

What is the difference between a Database and a Collection in MongoDB?

Answer: A database is a container that holds multiple collections, similar to a schema in SQL databases. A collection is a group of documents, similar to a table in SQL. For example, in an e-commerce app, you might have a database called "ecommerce" containing collections like "users", "products", and "orders". Each collection stores related documents in JSON-like format.

QUESTION 2

How do you create a database in MongoDB?

Answer: MongoDB creates databases implicitly when you first store data in them. You use the use command to switch to a database (creating it if it doesn't exist), but it won't actually appear in show dbs until you insert at least one document.

// Switch to (or create) database
use myshop
// Insert data to actually create it
db.products.insertOne({name: "Laptop"})
QUESTION 3

What are the default databases in MongoDB?

Answer: MongoDB comes with three default system databases:

  • admin - Administrative database for user authentication and authorization
  • local - Stores data specific to a single server (not replicated)
  • config - Stores sharding configuration for sharded clusters

Important: These databases should never be deleted or modified unless you know exactly what you're doing!

QUESTION 4

What is the difference between db.dropDatabase() and db.collection.drop()?

Answer: db.dropDatabase() deletes the entire current database and all its collections, while db.collection.drop() only deletes a specific collection within the database. Both operations are irreversible, so always backup your data before using them!

QUESTION 5

Can a collection exist without any documents?

Answer: Yes! If you create a collection explicitly using db.createCollection("name"), it exists even with zero documents. However, if you simply switch to a database with use dbName and reference a collection without inserting data, the collection won't actually be created until the first document is inserted.

QUESTION 6

What is the maximum size of a MongoDB database?

Answer: MongoDB databases have no hard size limit - they can grow as large as the available disk space allows. However, individual documents have a maximum size of 16 MB. For very large data sets, MongoDB uses sharding to distribute data across multiple servers, allowing virtually unlimited scaling.

QUESTION 7

Should you create separate databases for development and production?

Answer: Absolutely yes! Always maintain separate databases (or even separate MongoDB instances) for development, testing, staging, and production environments. This prevents accidental data corruption, allows safe testing of schema changes, and follows industry best practices. Most teams use database names like myapp_dev, myapp_staging, and myapp_prod.

QUESTION 8

What happens if you try to use a database that doesn't exist?

Answer: Nothing breaks! MongoDB will create the database automatically when you insert your first piece of data. The use command switches to the database (creating it in memory), but it won't physically exist until you perform a write operation like insertOne() or insertMany().

QUESTION 9

Explain the difference between a capped collection and a normal collection.

Answer: A capped collection is a fixed-size collection that automatically overwrites the oldest documents when it reaches its size limit. It maintains insertion order and is perfect for logs or cache data. A normal collection can grow unlimited and doesn't automatically delete old documents.

// Create capped collection (5MB max)
db.createCollection("logs", {
  capped: true,
  size: 5242880
})
QUESTION 10

How do you check which database you're currently using?

Answer: Simply type db in the MongoDB shell. This command returns the name of the current database. The db variable always points to your currently selected database.

mongosh> db
myshop