Truncating avgs in $bucket

Following from earlier lessons where we truncated averages in the $project stage, as I was following along w/ Chapter 4 I decided to try out some calculations on fields in the $bucket stage…

db.companies.aggregate([
{$match: {
founded_year: {$gt: 1980}
}},
{$bucket: {
groupBy: “$number_of_employees”,
boundaries: [ 0, 20, 50, 100, 500, 1000, Infinity],
default: ‘Other’,
output: {
total: {$sum: 1},
average: {$avg: “$number_of_employees”},
avg: {$divide: [{$trunc: {$avg: {$multiply: ["$number_of_employees", 10]}}}, 10]},
categories: {"$addToSet": “$category_code”}
}
}}
]).pretty()

This results in a “$divide is not a unary operation” which I know basically means it can’t be the outside operation on a field in the $group or $bucket stage.

I have to move on to something else so was just curious how I could tweak this code, what I might be missing here? Thanks.

Hi,

You are right, it expects an accumulator expression and $divide is not one of them. Using $addFields or a projection stage would allow you to trunc the result to 1 decimal.

`db.companies.aggregate([ 
     {$match: { founded_year: {$gt: 1980} }}, 
     {$bucket: { groupBy: "$number_of_employees", 
                       boundaries: [ 0, 20, 50, 100, 500, 1000, Infinity], 
                       default: "Other",
                       output: { 
                           total: {$sum: 1}, 
                           average: {$avg: "$number_of_employees"}, 
                           categories: {"$addToSet": "$category_code"} 
                       }
         }},
     {$addFields: {avg: {$divide: [{$trunc: {$avg: {$multiply: ["$average", 10]}}}, 10]}}} ]).pretty()`

José Carlos

Thanks, José Carlos. I should have gotten that. My mistake was that I was trying to do everything all in the same field. Appreciate the help.

Glad to help. :slightly_smiling_face:

José Carlos