MongoDB provides a powerful aggregation framework that enables users to process and analyze data using a set of pipeline stages. Here are some common aggregation pipeline stages in MongoDB:
1. **$match**: This stage filters documents based on specified conditions. It’s similar to the ‘find()‘ method where you can pass a query filter to retrieve documents from a collection.
Example: Suppose you have a collection of students and you want to retrieve all students who have a GPA greater than or equal to 3.5. This is how you would use the ‘$match‘ stage:
db.students.aggregate([
{ $match: { gpa: { $gte: 3.5 } } }
])
2. **$group**: This stage groups documents together based on a specified key and performs aggregate functions on each group.
Example: Let’s say you want to calculate the average GPA for each major in your student collection. You can use the ‘$group‘ stage like this:
db.students.aggregate([
{ $group: { _id: "$major", avgGpa: { $avg: "$gpa" } } }
])
In this example, the ‘_$id‘ field specifies the key to group by, and ‘$avg‘ calculates the average GPA for each group.
3. **$project**: This stage reshapes documents by including, excluding, or transforming fields.
Example: Suppose you only want to retrieve the student name, major, and GPA from the previous example. You can use ‘$project‘ like this:
db.students.aggregate([
{ $group: { _id: "$major", avgGpa: { $avg: "$gpa" } } },
{ $project: { _id: 0, major: "$_id", avgGpa: 1 } }
])
In this example, ‘$project‘ excludes the ‘_id‘ field and renames the ‘_id‘ field to ‘major‘.
4. **$sort**: This stage sorts documents based on a specified field or fields.
Example: Suppose you want to sort the students in descending order of their GPA. You can use ‘$sort‘ like this:
db.students.aggregate([
{ $sort: { gpa: -1 } }
])
In this example, ‘-1‘ specifies descending order. If you want ascending order, you can use ‘1‘.
5. **$limit**: This stage limits the number of documents in the pipeline.
Example: Suppose you only want to retrieve the top 10 students based on their GPA. You can use ‘$limit‘ like this:
db.students.aggregate([
{ $sort: { gpa: -1 } },
{ $limit: 10 }
])
In this example, ‘$sort‘ sorts students in descending order of their GPA and ‘$limit‘ restricts the pipeline to the top 10 students.
These are just a few common aggregation pipeline stages in MongoDB. There are many more stages available, such as ‘$unwind‘, ‘$lookup‘, ‘$addToSet‘, and more. The aggregation pipeline is a powerful and flexible tool for processing and analyzing data in MongoDB.