Problem Statement
In the aggregation pipeline, which accumulator operator calculates the average value?
Explanation
The dollar avg accumulator operator calculates the average value of numeric fields across grouped documents. It is commonly used within the dollar group stage to compute averages.
Other useful accumulator operators include dollar sum for totals, dollar min and dollar max for extremes, dollar first and dollar last for boundary values, and dollar push to create arrays of values. These operators work only within dollar group or dollar bucket stages.
Code Solution
SolutionRead Only
// Calculate average salary by department
db.employees.aggregate([
{
$group: {
_id: "$department",
avgSalary: { $avg: "$salary" },
count: { $sum: 1 }
}
}
])