Aggregation

Aggregation has the most important role in MongoDB. Aggregation operations process data records and return computed results. Aggregation operations group values from multiple documents together and can perform a variety of operations on the grouped data to return a single result.

to perform the aggregate function in MongoDB, aggregate () is the function to be used. Following is the syntax for aggregation :


db.collection_name.aggregate(aggregate_operation)

Employees collection

[
	{
		"_id" : ObjectId("5f26e736deec6e20ea057831"),
		"name" : "John",
		"age" : 35,
		"department" : "department A",
		"salary" : 200000
	},
	{
		"_id" : ObjectId("5f26e7c0deec6e20ea057832"),
		"name" : "Rom",
		"age" : 30,
		"department" : "department A",
		"salary" : 70000
	},
	{
		"_id" : ObjectId("5f26e9dedeec6e20ea057833"),
		"name" : "Tony",
		"age" : 31,
		"department" : "department B",
		"salary" : 40000
	},
	{
		"_id" : ObjectId("5f26e9dedeec6e20ea057834"),
		"name" : "Peter",
		"age" : 32,
		"department" : "department B",
		"salary" : 30000
	},
	{
		"_id" : ObjectId("5f26e9dedeec6e20ea057835"),
		"name" : "Andrew",
		"age" : 33,
		"department" : "department C",
		"salary" : 20000
	}
]

Now We want to get the total of employees corresponding to department wise.

 db.employees.aggregate([{$group : {_id : "$department", total_employee : {$sum : 1}}}])
 

Output:-

  { "_id" : "department C", "total_employee" : 1 }
  { "_id" : "department B", "total_employee" : 2 }
  { "_id" : "department A", "total_employee" : 2 }

 

Different Expression which is used by an aggregate function

Expression
Description
$sum
Sums up the defined value from all documents in the collection.
$min
Gets the minimum of the corresponding values from all documents in the collection.
$max
Gets the maximum of the corresponding values from all documents in the collection.
$avg
Calculates the average of all given values from all documents in the collection.
$push
Inserts the value to an array in the resulting document.
$pop
remove the value from an array in the resulting document.
$addToSet
Inserts the value to an array in the resulting document but does not create duplicates.
$first
Gets the first document from the source documents according to the grouping. Typically this makes only sense together with some previously applied “$sort”-stage.
$last
Gets the last document from the source documents according to the grouping. Typically this makes only sense together with some previously applied “$sort”-stage.