MongoDB Indexing and Aggregation
1. Indexing in MongoDB
Indexing in MongoDB improves the efficiency of queries by creating a data structure that stores a portion o
Types of Indexes in MongoDB:
1. Single Field Index: Index on a single field in a document.
db.collection.createIndex({ field: 1 }); // Ascending order
db.collection.createIndex({ field: -1 }); // Descending order
2. Compound Index: Index on multiple fields.
db.collection.createIndex({ field1: 1, field2: -1 });
3. Multikey Index: Index on fields containing arrays.
db.collection.createIndex({ tags: 1 });
4. Text Index: Index for text search.
db.collection.createIndex({ content: "text" });
5. Hashed Index: Index for hashed values, used in sharding.
db.collection.createIndex({ field: "hashed" });
6. Wildcard Index: Index on all fields or specific patterns.
db.collection.createIndex({ "$**": 1 });
Index Management Commands:
- View all indexes:
db.collection.getIndexes();
- Drop an index:
db.collection.dropIndex("indexName");
- Drop all indexes:
db.collection.dropIndexes();
Benefits of Indexing:
- Faster query execution.
- Optimized sorting.
- Improved performance for queries with large datasets.
Trade-offs:
- Indexes consume additional disk space.
- Indexes can slow down write operations (inserts, updates, deletes).
2. Aggregation in MongoDB
Aggregation is a powerful framework for processing and transforming data in MongoDB. It allows you to pe
Aggregation Pipeline:
The aggregation pipeline is a series of stages where each stage processes and transforms the data.
Basic Syntax:
db.collection.aggregate([
{ stage1 },
{ stage2 },
{ stage3 }
]);
Common Aggregation Stages:
1. $match: Filters documents based on a condition.
{ $match: { status: "active" } }
2. $group: Groups documents and performs aggregations.
{ $group: { _id: "$category", total: { $sum: "$amount" } } }
3. $project: Reshapes the document by including or excluding fields.
{ $project: { name: 1, total: { $multiply: ["$price", "$quantity"] } } }
4. $sort: Sorts documents in ascending or descending order.
{ $sort: { total: -1 } }
5. $limit: Limits the number of documents.
{ $limit: 5 }
6. $skip: Skips a specified number of documents.
{ $skip: 10 }
7. $unwind: Deconstructs arrays into multiple documents.
{ $unwind: "$tags" }
8. $lookup: Performs a left outer join with another collection.
{
$lookup: {
from: "orders",
localField: "userId",
foreignField: "_id",
as: "userOrders"
Example: Aggregation Pipeline
db.orders.aggregate([
{ $match: { status: "shipped" } },
{ $group: { _id: "$customerId", totalSpent: { $sum: "$amount" } } },
{ $sort: { totalSpent: -1 } },
{ $limit: 5 }
]);
This query:
1. Filters orders with status: "shipped".
2. Groups orders by customerId and calculates the total amount spent.
3. Sorts customers by their total spending in descending order.
4. Limits the result to the top 5 customers.
Indexing and Aggregation Together:
Indexes improve the performance of aggregation pipelines, especially for stages like $match and $sort. For
- If $match is the first stage in the pipeline, MongoDB uses the index to filter documents efficiently.
- Sorting on indexed fields speeds up the $sort stage.
By combining indexing and aggregation, you can handle large datasets efficiently and perform complex que