MongoDB Aggregation

Aggregation process returns an average of all numeric values seen during the group and project. It ignores non numeric values.

Syntax of Aggregation($avg) - used in $group

{ $avg: expression }

It returns the collective average of all numeric values that result from applying a specified expression to each document in a group of documents. It is available in the group and project stages.

Syntax of Aggregation($avg) - used in $project

{ $avg: [expression1, expression2,..]}

It returns the average of the specified expression or list of expressions for each document. It is available in the group and project stages.





MongoDB Aggregate Example

Suppose, we have following collection, we want to get the average product amount and average quantity.

db.product.insert([
{'item': 'iron', 'price': 120, 'quantity': 2}, 
{'item':'alloy', 'price':90, 'quantity': 1}, 
{'item':'steel', 'price':47, 'quantity': 3}, 
{'item':'alloy', 'price':70, 'quantity': 6}, 
{'item':'iron', 'price':56, 'quantity':4}
]);

The following statement returns the average product amount and average quantity.

db.product.aggregate(
[{
	"$group" : {
		"_id": "$item",
		avgAmt: { $avg: {$multiply: ["$price", "$quantity"]}},
		avgQty: { $avg: "$quantity"}
	}
}]
) 
mongodb average





Read more articles