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

查看:32
本文介绍了如何在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]}] }}} )

如果您想下限为 10 或 1000,请使用 10 或 1000 而不是 1.

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

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

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