MongoDB Aggregation Pipelines
Introduction
Learn how to perform complex data aggregation operations in MongoDB using the aggregation pipeline framework.
Connecting to MongoDB
Before starting aggregation operations, ensure you are connected to your MongoDB server:
Example: Connecting to MongoDB
mongosh
This command starts the mongosh
shell and connects to the default MongoDB server running locally.
Switching to a Database
Switch to the database where your collection resides using the use
command:
Example: Switching to a Database
use mydatabase
This command switches to the “mydatabase” database. Replace mydatabase
with your database name.
Aggregation Pipeline Stages
Construct aggregation pipelines using various stages:
- $match: Filters documents based on specified criteria.
- $group: Groups documents by a specified identifier.
- $project: Reshapes documents by including, excluding, or adding fields.
- $sort: Sorts documents based on specified fields.
- $limit: Limits the number of documents passed to the next stage.
- $skip: Skips a specified number of documents before passing to the next stage.
- $unwind: Deconstructs an array field from documents and outputs one document for each element.
Examples
Here are some examples of MongoDB aggregation pipelines:
Example: Aggregating Data
db.mycollection.aggregate([
{ $match: { status: "active" } },
{ $group: { _id: "$category", total: { $sum: "$quantity" } } }
])
This pipeline filters documents where status
is “active”, groups them by category
, and calculates the total quantity for each category.
Example: Sorting Results
db.mycollection.aggregate([
{ $sort: { age: 1 } }
])
This pipeline sorts documents in ascending order based on the age
field.
Executing Aggregation
Execute aggregation pipelines using the aggregate
method:
Example: Executing Aggregation
db.mycollection.aggregate(pipeline)
Replace pipeline
with your aggregation pipeline array defined earlier.
Conclusion
The MongoDB aggregation framework provides powerful tools for data aggregation, allowing you to perform complex operations directly within the database. Experiment with different stages and operators to achieve the desired data transformations and analysis.