繁体   English   中英

用 MongoDB 聚合 $group 结果计数

[英]Count with MongoDB aggregate $group result

我有一个pymongo的数据库查询,就像这样

pipeline = [
    {"$group": {"_id": "$product", "count": {"$sum": 1}}},
]
rows = list(collection_name.aggregate(pipeline))
print(rows)

结果喜欢

[
    {'_id': 'p1', 'count': 45},
    {'_id': 'p2', 'count': 4},
    {'_id': 'p3', 'count': 96},
    {'_id': 'p1', 'count': 23},
    {'_id': 'p4', 'count': 10}
]

目的

基于以上结果,我想进行分区间的统计。 例如,获取以下区间内的计数次数:

partition, count
(0, 10], 2
[11, 50), 2
[50, 100], 1

有没有办法完全使用 MongoDB 聚合框架来做到这一点?

任何评论都会非常有帮助。 谢谢。


@Wernfried Domscheit 的回答

$bucket

pipeline = [
    {"$group": {"_id": "$product", "count": {"$sum": 1}}},
    {"$bucket": {
        "groupBy": "$count",
        "boundaries": [0, 11, 51, 100],
        "default": "Other",
        "output": {
            "count": {"$sum": 1},
        }
    }}
]
rows = list(tbl_athletes.aggregate(pipeline))
rows

$bucketAuto

pipeline = [
    {"$group": {"_id": "$product", "count": {"$sum": 1}}},
    {"$bucketAuto": {
        "groupBy": "$count",
        "buckets": 5,
        "output": {
            "count": {"$sum": 1},
        }
    }}
]
rows = list(tbl_athletes.aggregate(pipeline))
rows

注意:

$bucket中, default必须存在。

是的,你有$bucket运营商:

db.collection.aggregate([
   {
      $bucket: {
         groupBy: "$count",
         boundaries: [0, 11, 51, 100],
         output: {
            count: { $sum: 1 },
         }
      }
   }
])

或者使用自动生成间隔的$bucketAuto

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM