计算 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}
]

Objective:

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

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

注意:

$bucketdefault一定要有

是的,您有 $bucket 运算符:

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

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