Mastering the MongoDB Aggregation Framework: Basics to Advanced
Mastering the MongoDB Aggregation Framework: Basics to Advanced
The MongoDB Aggregation Framework is a powerful tool for performing complex data transformations and computations. This guide covers the basics and advanced features of the Aggregation Pipeline.
What is Aggregation?
- Aggregation is a process of transforming data from a collection into aggregated results. It involves processing data records and returning computed results.
Aggregation Pipeline:
- A framework for data processing in MongoDB. It processes data through a series of stages that transform the data into the desired format.
Aggregation Stages
$match:
- Purpose: Filters documents based on specified criteria.
> db.orders.aggregate([{ $match: { status: "shipped" } }])
$group:
- Purpose: Groups documents by a specified field and performs aggregations (e.g., sum, average).
> db.orders.aggregate([
{ $group: { _id: "$category", totalAmount: { $sum: "$amount" } } }
])
$sort:
- Purpose: Sorts documents by specified fields.
> db.orders.aggregate([{ $sort: { totalAmount: -1 } }])
$project:
- Purpose: Reshapes documents by including or excluding fields.
> db.orders.aggregate([{ $project: { item: 1, totalAmount: 1 } }])
$limit:
- Purpose: Limits the number of documents passed to the next stage.
> db.orders.aggregate([{ $limit: 5 }])
$skip:
- Purpose: Skips a specified number of documents.
> db.orders.aggregate([{ $skip: 5 }])
Complex Aggregations:
$lookup:
- Purpose: Performs a left outer join to another collection.
> db.orders.aggregate([
{
$lookup: {
from: "products",
localField: "productId",
foreignField: "_id",
as: "productDetails"
}
}
])
$unwind:
- Purpose: Deconstructs an array field from the input documents.
> db.orders.aggregate([{ $unwind: "$items" }])
$arrayElemAt:
- Purpose: Returns the element at a specified array index.
> db.orders.aggregate([
{ $project: { firstItem: { $arrayElemAt: ["$items", 0] } } }
])
MongoDB Aggregation Framework, MongoDB Aggregation Pipeline, MongoDB $match, MongoDB $group, MongoDB $sort, MongoDB $project, MongoDB $lookup, MongoDB $unwind.