计算MongoDB聚合框架中的中位数 [英] Calculate the median in MongoDB aggregation framework
问题描述
是否有一种使用MongoDB聚合框架计算中位数的方法?
Is there a way to calculate the median using the MongoDB aggregation framework?
推荐答案
在一般情况下,中位数在计算时有些棘手,因为它涉及对整个数据集进行排序,或者使用深度也与数据集大小.这也许就是为什么许多数据库没有开箱即用的中间值运算符(MySQL也没有)的原因.
The median is somewhat tricky to compute in the general case, because it involves sorting the whole data set, or using a recursion with a depth that is also proportional to the data set size. That's maybe the reason why many databases don't have a median operator out of the box (MySQL doesn't have one, either).
计算中位数的最简单方法是使用以下两个语句(假设我们要在其上计算中位数的属性称为a
,并且希望在集合中的所有文档coll
上使用它):
The simplest way to compute the median would be with these two statements (assuming the attribute on which we want to compute the median is called a
and we want it over all documents in the collection, coll
):
count = db.coll.count();
db.coll.find().sort( {"a":1} ).skip(count / 2 - 1).limit(1);
这等同于人们建议使用MySQL .
这篇关于计算MongoDB聚合框架中的中位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!