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

Roman Dibikhin
- 856
- 4
- 15
-
Possible duplicate of [Is there a floor function in Mongodb aggregation framework?](http://stackoverflow.com/questions/13617526/is-there-a-floor-function-in-mongodb-aggregation-framework) – Salvador Dali Nov 13 '15 at 07:02
2 Answers
7
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.

Roman Dibikhin
- 856
- 4
- 15
0
Since mongoDB version 3.2 there is a $floor
function, so you can simply use:
db.users.aggregate([
{$group: {_id: {$floor: "$age"}}}
])

nimrod serok
- 14,151
- 2
- 11
- 33