Your comprehensive guide to NoSQL document databases. Learn CRUD operations, aggregation pipelines, indexing strategies, and cloud deployment with MongoDB Atlas.
Understanding MongoDB architecture and components
MongoDB is a powerful NoSQL document-oriented database that stores data in JSON-like documents (actually BSON - Binary JSON). Unlike traditional SQL databases, MongoDB offers flexible schemas and horizontal scalability.
E-commerce Example: We'll use an online store with Products, Orders, and Contacts collections throughout this guide.
The database server daemon handling connections and storage
Command-line interface for interactive database operations
GUI tool for visual data exploration and query building
// Database Operations
show dbs // List all databases
use ecommerce // Switch/create database
show collections // List collections
db.dropDatabase() // Delete current database
// 💡 Pro Tip: 'use' creates DB only after first insert
cloud.mongodb.com
Create, Read, Update, and Delete documents
Insert documents into collections. MongoDB automatically creates collections if they don't exist.
// Insert Products
db.products.insertMany([
{
name: "Wireless Mouse",
price: 799,
category: "Electronics",
stock: 120,
ratings: 4.5,
tags: ["computer", "accessory"],
createdAt: new Date()
},
{
name: "Mechanical Keyboard",
price: 2499,
category: "Electronics",
stock: 80,
ratings: 4.8,
tags: ["keyboard", "mechanical"],
createdAt: new Date()
}
])
// Insert Orders
db.orders.insertMany([
{
orderId: "ORD001",
user: "John Doe",
products: [
{ name: "Wireless Mouse", qty: 1, price: 799 }
],
total: 3298,
status: "Delivered",
createdAt: new Date()
}
])
// Basic Find
db.products.find()
db.products.find().pretty()
// Filter by Field
db.products.find({ category: "Electronics" })
// Comparison Operators
db.products.find({ price: { $gt: 1000 } })
db.products.find({
price: { $gte: 1000, $lte: 50000 }
})
// Logical Operators
db.products.find({
$or: [
{ category: "Electronics" },
{ stock: { $lt: 50 } }
]
})
// Projection (Select Fields)
db.products.find(
{},
{ name: 1, price: 1, _id: 0 }
)
// Sort & Limit
db.products.find()
.sort({ price: -1 })
.limit(2)
Query documents using various operators and options. Use projection to limit returned fields.
$eq
Equals
$gt/$gte
Greater than
$lt/$lte
Less than
$in
Match array
$or/$and
Logical
$regex
Pattern match
Modify existing documents using update operators. Always use specific filters to avoid unintended updates.
$set
Set field value
$inc
Increment/decrement numbers
$push/$pull
Add/remove from arrays
$unset
Remove field
// Update One Document
db.products.updateOne(
{ name: "Wireless Mouse" },
{ $set: { price: 899 } }
)
// Update Many Documents
db.products.updateMany(
{ category: "Electronics" },
{ $inc: { stock: 10 } }
)
// Add to Array
db.products.updateOne(
{ name: "Wireless Mouse" },
{ $push: { tags: "wireless" } }
)
// Remove from Array
db.products.updateOne(
{ name: "Wireless Mouse" },
{ $pull: { tags: "old" } }
)
// Remove Field
db.products.updateOne(
{ name: "Wireless Mouse" },
{ $unset: { temporaryField: "" } }
)
Delete operations are permanent! Always test your query
with find() before using
deleteMany().
// Delete One
db.contacts.deleteOne({ name: "Alice" })
// Delete Many
db.orders.deleteMany({ status: "Delivered" })
// ⚠️ Danger: Delete All (Use with caution!)
db.collection.deleteMany({})
Powerful data processing pipelines
Aggregation pipelines analyze and transform data through stages. Each stage performs an operation, passing results to the next stage like an assembly line. MongoDB supports over 25 aggregation stages!
// Total Revenue Calculation
db.orders.aggregate([
{
$group: {
_id: null,
totalRevenue: { $sum: "$total" },
avgOrder: { $avg: "$total" },
count: { $sum: 1 }
}
}
])
// Group by Status
db.orders.aggregate([
{
$group: {
_id: "$status",
totalOrders: { $sum: 1 },
revenue: { $sum: "$total" }
}
},
{ $sort: { revenue: -1 } }
])
// Lookup (Join) Example
db.orders.aggregate([
{
$lookup: {
from: "products",
localField: "products.name",
foreignField: "name",
as: "productDetails"
}
}
])
$match
Filter documents (like find() query)
$group
Group by field and calculate aggregates (sum, avg, etc.)
$project
Select fields, create computed fields
$sort/$limit
Sort results and limit output
db.sales.aggregate([
// Stage 1: Filter for specific category
{ $match: { category: "Electronics" } },
// Stage 2: Calculate total per item
{
$project: {
item: 1,
totalRevenue: { $multiply: ["$price", "$quantity"] }
}
},
// Stage 3: Group by category and sum
{
$group: {
_id: "$category",
totalSales: { $sum: "$totalRevenue" },
avgPrice: { $avg: "$price" },
count: { $sum: 1 }
}
},
// Stage 4: Sort by revenue descending
{ $sort: { totalSales: -1 } },
// Stage 5: Limit to top 3
{ $limit: 3 }
])
Performance, indexing, and administration
Indexes improve read operation speed by allowing MongoDB to locate data without scanning every document. However, they slow down writes.
// Create Index
db.products.createIndex({ name: 1 }) // 1 = ascending, -1 = descending
// Compound Index
db.products.createIndex({ category: 1, price: -1 })
// View Indexes
db.products.getIndexes()
// Analyze Query Performance
db.products.find({ price: { $gt: 5000 } })
.explain("executionStats")
Trade-off: While indexes improve read performance, they slow down write operations (inserts, updates, deletes) because the index must also be updated.
db.stats()
Database statistics
db.serverStatus()
Server metrics
db.collection.count()
Document count
db.collection.drop()
Delete collection
Design schemas based on query patterns, not just structure. Embed data accessed together.
Index frequently queried fields. Use explain() before adding indexes.
Use projection to return only needed fields. Limit results when possible.
Essential commands at a glance
insertOne()
Create single
insertMany()
Create multiple
find()
Read multiple
findOne()
Read single
updateOne()
Update single
updateMany()
Update multiple
deleteOne()
Delete single
deleteMany()
Delete multiple
$eq
Equal to
$gt / $gte
Greater than
$lt / $lte
Less than
$in
Match any in array
$or / $and
Logical operators
$regex
Pattern matching
$set
Update field
$inc
Increment
$match
Filter documents
$group
Group & aggregate
$project
Shape output
$sort
Order results
$limit
Restrict output
$lookup
Join collections
$unwind
Deconstruct array
$facet
Multi-stage pipelines