💔 Accumulator:
In the MongoDB Aggregation framework, accumulators are the operator that performs different accumulation operation during the aggregation pipeline.
Most of the accumulators are used in the $group stage.
💢 Syntax:
{ $group: { _id: <grouping expression>, <accumulator operator>: <expression> } }
Here are some commonly used accumulator operators in the MongoDB Aggregation Framework:
$sum
: Calculates the sum of numeric values within a group.$avg
: Computes the average of numeric values within a group.$min
: Returns the minimum value of numeric or date values within a group.$max
: Returns the maximum value of numeric or date values within a group.$first
: Returns the first value in a group.$last
: Returns the last value in a group.$push
: Gathers values into an array.$addToSet
: Adds unique values to an array.$stdDevPop
: Computes the population standard deviation.$stdDevSamp
: Computes the sample standard deviation.
$sum:
db.getCollection("persons").aggregate([
{$group: {"_id": "$age", total: {$sum:1}}}
]);
Using
$sum: 1
is a technique to count the occurrences of documents within a group or in each group.db.getCollection("persons").aggregate([
{$group: {"_id": "$age", total: {$sum:"$age"}}}
]);
Using
$sum: <expression>
to calculate the values of documents in each group.$avg:
The $avg accumulator is used to calculate the average of numeric values in each group.
Syntax:
{
$group: {
_id: <grouping_field>,
averageValue: { $avg: <numeric_field> }
}
}
Example:
db.getCollection("products").aggregate([
{$group: {"_id": {brand: "$brand"}, total: {$avg: "$price"}}},
]);
Post a Comment