MongoDB Aggregation Framework - Accumulator

💔 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:

  1. $sum: Calculates the sum of numeric values within a group.
  2. $avg: Computes the average of numeric values within a group.
  3. $min: Returns the minimum value of numeric or date values within a group.
  4. $max: Returns the maximum value of numeric or date values within a group.
  5. $first: Returns the first value in a group.
  6. $last: Returns the last value in a group.
  7. $push: Gathers values into an array.
  8. $addToSet: Adds unique values to an array.
  9. $stdDevPop: Computes the population standard deviation.
  10. $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

Previous Post Next Post