Professional Documents
Culture Documents
Aggregation
Aggregation
Aggregation in NoSQL:
Aggregation operations process multiple documents and return computed results. You
can use aggregation operations to:
db.customer.insertMany([
{ _id: 3, name: "Charlie", age: 21, score: 78 },
{ _id: 4, name: "David", age: 23, score: 88 },
{ _id: 5, name: "Emma", age: 20, score: 95 },
{ _id: 6, name: "Frank", age: 22, score: 75 },
{ _id: 7, name: "Grace", age: 21, score: 90 },
{ _id: 8, name: "Hannah", age: 22, score: 82 },
{ _id: 9, name: "Ivy", age: 20, score: 89 },
{ _id: 10, name: "Jack", age: 23, score: 91 },
{ _id: 11, name: "Katherine", age: 21, score: 87 },
{ _id: 12, name: "Leo", age: 22, score: 79 },
// Add more student documents here...
]);
-----------------------------------------------------------------------------------
-------
$match
Filters the documents to pass only the documents that match the specified
condition(s) to the next pipeline stage.
{ $match: { <query> } }
db.customer.aggregate([
{
$match: { age: { $gte: 21 } }
}
]);
$group
The $group stage separates documents into groups according to a "group key". The
output is one document for each unique group key.
db.students.aggregate([
{
$sort: { name: 1 }
}
]);
Example 2: Sort Documents by a Single Field in Descending Order
db.students.aggregate([
{
$sort: { age: -1 }
}
]);
Example 3: Sort Documents by Multiple Fields
db.students.aggregate([
{
$sort: { age: 1, score: -1 }
}
]);