How to aggregate by floor in MongoDB

六眼飞鱼酱① 提交于 2019-11-27 08:05:35

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/32554156/how-to-aggregate-by-floor-in-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!