Aggregation Pipeline Method
To understand Aggregation Pipeline Method Let’s imagine a collection named users
with some documents for our examples.
{
"_id": ObjectId("60a3c7e96e06f64fb5ac0700"),
"name": "Alice",
"age": 30,
"email": "alice@example.com",
"city": "New York"
}
{
"_id": ObjectId("60a3c7e96e06f64fb5ac0701"),
"name": "Bob",
"age": 35,
"email": "bob@example.com",
"city": "Los Angeles"
}
{
"_id": ObjectId("60a3c7e96e06f64fb5ac0702"),
"name": "Charlie",
"age": 25,
"email": "charlie@example.com",
"city": "Chicago"
}
1. $group
: It Groups documents by the city
field and calculates the average age using the $avg
accumulator.
db.users.aggregate([
{ $group: { _id: "$city", averageAge: { $avg: "$age" } } }
])
Output:
[
{ _id: 'New York', averageAge: 30 },
{ _id: 'Chicago', averageAge: 25 },
{ _id: 'Los Angeles', averageAge: 35 }
]
2. $project: Include or exclude fields from the output documents.
db.users.aggregate([
{ $project: { name: 1, city: 1, _id: 0 } }
])
Output:
[
{ name: 'Alice', city: 'New York' },
{ name: 'Bob', city: 'Los Angeles' },
{ name: 'Charlie', city: 'Chicago' }
]
$match: Filter documents to pass only those that match the specified condition(s).
db.users.aggregate([
{ $match: { age: { $gt: 30 } } }
])
Output:
[
{
_id: ObjectId('60a3c7e96e06f64fb5ac0701'),
name: 'Bob',
age: 35,
email: 'bob@example.com',
city: 'Los Angeles'
}
]
3. $sort: It Order the documents.
db.users.aggregate([
{ $sort: { age: 1 } }
])
Output:
[
{
_id: ObjectId('60a3c7e96e06f64fb5ac0702'),
name: 'Charlie',
age: 25,
email: 'charlie@example.com',
city: 'Chicago'
},
{
_id: ObjectId('60a3c7e96e06f64fb5ac0700'),
name: 'Alice',
age: 30,
email: 'alice@example.com',
city: 'New York'
},
{
_id: ObjectId('60a3c7e96e06f64fb5ac0701'),
name: 'Bob',
age: 35,
email: 'bob@example.com',
city: 'Los Angeles'
}
]
4. $limit: Limit the number of documents passed to the next stage.
db.users.aggregate([
{ $limit: 2 }
])
Output:
[
{
_id: ObjectId('60a3c7e96e06f64fb5ac0700'),
name: 'Alice',
age: 30,
email: 'alice@example.com',
city: 'New York'
},
{
_id: ObjectId('60a3c7e96e06f64fb5ac0701'),
name: 'Bob',
age: 35,
email: 'bob@example.com',
city: 'Los Angeles'
}
]
Aggregation in MongoDB
Aggregation in MongoDB is a powerful feature that allows for complex data transformations and computations on collections of documents. It enables users to group, filter, and manipulate data to produce summarized results.
It is typically performed using the MongoDB Aggregation Pipeline which is a framework for data aggregation modeled on the concept of data processing pipelines. In this article, We will learn about Aggregation in MongoDB in detail by covering various aspects related to MongoDB Aggregation.