Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to aggregate by floor in MongoDB

MongoDB Aggregation Framework doesn't have floor function. It only has simple arithmetic operators. So, how to compose floor function using them?

like image 384
Roman Dibikhin Avatar asked Feb 01 '26 01:02

Roman Dibikhin


1 Answers

According to definition floor(number) = number - (number % step) we can compose our aggregation formula:

{$subtract: ["$number", {$mod: ["$number", <step>]}]}

where step is order of magnitude. First, it computes remainder with $mod and then it computes difference with $subtract.

So, grouping Users by age floored to whole numbers will be

db.users.aggregate(
    {$group: {_id: {$subtract: ["$age", {$mod: ["$age", 1]}] }}} )

If you want to floor to 10s or 1000s use 10 or 1000 instead of 1.

like image 174
Roman Dibikhin Avatar answered Feb 02 '26 14:02

Roman Dibikhin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!