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

查看:16
本文介绍了如何在 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天全站免登陆