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
| Stage | Purpose / Function |
|---|---|
| $match | Filter documents |
| $project | Select/compute fields |
| $set / $addFields | Add or modify fields |
| $unset | Remove fields |
| $group | Group and calculate aggregates ($sum, $avg, $max, $min) |
| $sort | Sort pipeline results |
| $limit | Limit document count |
| $skip | Skip document count |
| $unwind | Expand array elements into separate documents |
| $lookup | Left outer join to another collection |
| $facet | Execute multiple aggregation sub-pipelines |
| $count | Count documents passing through stage |
| $sample | Random sample of documents |
| $replaceWith | Replace root document with expression result |
| $merge | Write pipeline results to collection (upsert/insert) |
| $out | Write 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 }
])