Created by Gagan Sir
Module 04: Indexes, Optimization & Core Aggregation Pipeline
MongoDB Shell + MQL + Aggregation + Administration + Python & Node.js Drivers + Real-World Projects
24
Index Basics
// Create ascending index db.students.createIndex({ email: 1 }) // Inspect indexes db.students.getIndexes() // Drop specific index db.students.dropIndex({ email: 1 }) // Drop all non-id indexes db.students.dropIndexes()
25
Compound Index
db.students.createIndex({ course: 1, age: -1 })
26
Unique, Sparse and Partial Indexes
// Unique Index db.users.createIndex({ email: 1 }, { unique: true }) // Sparse Index db.users.createIndex({ phone: 1 }, { sparse: true }) // Partial Index db.users.createIndex( { email: 1 }, { unique: true, partialFilterExpression: { active: true } } )
27
TTL (Time-To-Live) Index
db.sessions.createIndex( { createdAt: 1 }, { expireAfterSeconds: 3600 } )
28
Index Inspection & Query Execution Explanation
db.students.getIndexes() db.students.aggregate([ { $indexStats: {} } ]) db.students.find({ email: "aman@example.com" }).explain("executionStats")
29
Hint Operator
db.students.find({ course: "MCA" }).hint({ course: 1 })
30
Aggregation Pipeline Syntax
db.collection.aggregate([ { stage1: { /* ... */ } }, { stage2: { /* ... */ } }, { stage3: { /* ... */ } } ])
31
Core Aggregation Stages Reference
StagePurpose / Function
$matchFilter documents
$projectSelect/compute fields
$set / $addFieldsAdd or modify fields
$unsetRemove fields
$groupGroup and calculate aggregates ($sum, $avg, $max, $min)
$sortSort pipeline results
$limitLimit document count
$skipSkip document count
$unwindExpand array elements into separate documents
$lookupLeft outer join to another collection
$facetExecute multiple aggregation sub-pipelines
$countCount documents passing through stage
$sampleRandom sample of documents
$replaceWithReplace root document with expression result
$mergeWrite pipeline results to collection (upsert/insert)
$outWrite pipeline results to target collection
32
$match + $project Pipeline Example
db.orders.aggregate([ { $match: { status: "paid" } }, { $project: { customer: 1, amount: 1, _id: 0 } } ])
33
$group Sales Aggregation Example
db.orders.aggregate([ { $group: { _id: "$customer", totalSales: { $sum: "$amount" }, avgOrder: { $avg: "$amount" }, orders: { $sum: 1 } } } ])
34
$sort + $limit Pipeline Example
db.orders.aggregate([ { $sort: { amount: -1 } }, { $limit: 10 } ])