skip to content
Alvin Lucillo

Basic numeric aggregation stage

/ 1 min read

A basic aggregation on numeric values is sum and avg. The pipeline below accepts a $group stage where exam_type is the group key. All documents are grouped into their exam_type, with one result per exam_type. _id in the result holds the exam_type value. The other properties, sum and avg, take in an accumulators/operators and expression. For example, sum has $sum performs calculation to get the sum of $score values. $score refers to the score property.

// test data
db.getCollection("students").insertMany([
	{ student_id: 1, name: "Student1", class: "A" },
	{ student_id: 2, name: "Student2", class: "A" },
	{ student_id: 3, name: "Student3", class: "B" },
	{ student_id: 4, name: "Student4", class: "B" },
]);

db.getCollection("exams").insertMany([
	{ student_id: 1, exam_type: "midterm", score: 88 },
	{ student_id: 1, exam_type: "final", score: 92 },
	{ student_id: 2, exam_type: "midterm", score: 73 },
	{ student_id: 3, exam_type: "midterm", score: 80 },
	{ student_id: 3, exam_type: "final", score: 85 },
	{ student_id: 4, exam_type: "final", score: 61 },
]);

db.exams.aggregate([
	{
		$group: {
			_id: "$exam_type",
			sum: { $sum: "$score" },
			avg: { $avg: "$score" },
		},
	},
]);

Output:

[
	{
		"_id": "midterm",
		"sum": 241,
		"avg": 80.33333333333333
	},
	{
		"_id": "final",
		"sum": 238,
		"avg": 79.33333333333333
	}
]