Using the Aggregation Framework
Using the aggregation framework in MongoDB
The aggregation framework in MongoDB is a powerful tool for performing data processing and transformation tasks. It allows you to create complex pipelines to filter, sort, group, reshape, and modify data in a collection.
Aggregation Pipeline
The aggregation pipeline consists of a series of stages, each performing an operation on the input data and passing the result to the next stage. Common stages include:
- $match: Filters documents based on a specified condition.
- $group: Groups documents by a specified field and performs aggregations.
- $project: Reshapes documents by including, excluding, or adding new fields.
- $sort: Sorts documents by a specified field.
- $limit: Limits the number of documents in the output.
Example: Aggregation Pipeline
Below is an example of an aggregation pipeline that filters, groups, and sorts documents:
Aggregation Pipeline Example
db.collection.aggregate([
{ $match: { status: "active" } },
{ $group: { _id: "$category", total: { $sum: "$amount" } } },
{ $sort: { total: -1 } },
{ $limit: 5 }
])
Advanced Aggregation Operations
The aggregation framework also supports advanced operations such as:
- $lookup: Performs a left outer join with another collection.
- $unwind: Deconstructs an array field into multiple documents.
- $out: Writes the results of the aggregation to a new collection.
Example: $lookup Operation
Below is an example of using the $lookup operation to join two collections:
$lookup Example
db.orders.aggregate([
{
$lookup: {
from: "customers",
localField: "customerId",
foreignField: "_id",
as: "customerDetails"
}
}
])
