MongoDB Aggregation - SUM, MAX, MIN, AVG

Author: Al-mamun Sarkar Date: 2020-09-13 16:45:08

In this lesson, I will show you how to perform aggregations such as (SUM, MAX, MIN, AVG, PUSH, addToSet, FRIST, LAST) on MongoDB query.

 

SUM:

db.employees.aggregate([ { $group: { _id: "$phone", total: { $sum: "$salary" } } } ])

MAX:

db.employees.aggregate([ { $group: { _id: "$phone", total: { $max: "$salary" } } } ])

MIN:

db.employees.aggregate([ { $group: { _id: "$phone", total: { $min: "$salary" } } } ])

AVG:

db.employees.aggregate([ { $group: { _id: "$phone", total: { $avg: "$salary" } } } ])

PUSH:

db.employees.aggregate([ { $group: { _id: "$phone", total: { $push: "$salary" } } } ])

addToSet:

db.employees.aggregate([ { $group: { _id: "$phone", total: { $addToSet: "$salary" } } } ])

First:

db.employees.aggregate([ { $group: { _id: "$phone", total: { $first: "$salary" } } } ])

Last:

db.employees.aggregate([ { $group: { _id: "$phone", total: { $last: "$salary" } } } ])