MongoDB_Indexing_Aggregation
MongoDB_Indexing_Aggregation
1. Indexing in MongoDB
Indexing in MongoDB improves the efficiency of queries by creating a data structure that stores a portion o
db.collection.getIndexes();
- Drop an index:
db.collection.dropIndex("indexName");
db.collection.dropIndexes();
Benefits of Indexing:
- Optimized sorting.
Trade-offs:
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 }
]);
{ $sort: { total: -1 } }
{ $limit: 5 }
{ $skip: 10 }
{ $unwind: "$tags" }
$lookup: {
from: "orders",
localField: "userId",
foreignField: "_id",
as: "userOrders"
db.orders.aggregate([
{ $sort: { totalSpent: -1 } },
{ $limit: 5 }
]);
This query:
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.