如何在MongoDB中按楼层汇总 [英] How to aggregate by floor in MongoDB

查看:50
本文介绍了如何在MongoDB中按楼层汇总的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MongoDB聚合框架不具有floor功能. 它只有简单的算术运算符. 那么,如何使用它们组成floor函数呢?

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

推荐答案

根据定义floor(number) = number - (number % step),我们可以编写聚合公式:

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

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

其中,step是数量级.首先,它使用$mod计算余数,然后使用$subtract计算差异.

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

因此,将按age划分为整个个数字的用户分组为

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

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

如果您想降低到10s或1000s,请使用10或1000而不是1.

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

这篇关于如何在MongoDB中按楼层汇总的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆