Calculate the median in MongoDB aggregation framework

后端 未结 5 1210
广开言路
广开言路 2020-12-24 12:52

Is there a way to calculate the median using the MongoDB aggregation framework?

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-24 13:21

    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).

    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);
    

    This is the equivalent to what people suggest for MySQL.

提交回复
热议问题