MongoDB 独立聚合集合中的两个字段并计数

MongoDB Aggregate two fields from collection independently and count

我的 MongoDB 集合中的数据如下所示:

{id: 11111, up: 450000, down: 452000}

我目前能够按其中一个字段进行分组并通过执行以下操作进行计数(我使用的是 PyMongo):

    {
        "$group": {
            "_id": {"up": "$up",},
            "count": {"$sum": 1}
        }
    },
    {"$project": {"_id": 0, "label": "$_id.up", "count": "$count"}},


    {"$sort": {"label": 1}},
    {"$match": {"count": {"$gt": 0}}},

这给了我以下结果:

{
   {
      "count": 35,
      "label": 450000
   }
}

我正在尝试让“向上”和“向下”字段以下列格式显示:

{
   {
      "count": 35,
      "label": 450000
   },
   {
      "count": 35,
      "label": 452000
   }
}

希望有人能帮我执行这个查询。我能做到的最接近的方法是将“up”和“down”都放在“label”下的数组中,但我希望它们彼此独立。

谢谢!

我们可以$project$objectToArray to split up and down into an array of objects then $unwind得到上下分开的文档,然后按照上面的方法按标签统计即可:

db.collection.aggregate([
    {
        "$project": {
            "updown": {
                "$objectToArray": {
                    "up": "$up",
                    "down": "$down"
                }
            }
        }
    },
    {"$unwind": "$updown"},
    {
        "$group": {
            "_id": {
                "label": "$updown.v"
            },
            "count": {"$sum": 1}
        }
    },
    {"$project": {"_id": 0, "label": "$_id.label", "count": "$count"}},
    {"$sort": {"label": 1}},
    {"$match": {"count": {"$gt": 0}}}
])

结果:

[
    {"count": 4, "label": 450000},
    {"count": 2, "label": 452000},
    {"count": 2, "label": 462000}
]

mongoplayground

示例数据设置:

from pymongo import MongoClient

client = MongoClient()
db = client.test

# Remove Collection if exists
db.collection.drop()
# Insert Sample Data
db.collection.insert_many([{'id': 11111, 'up': 450000, 'down': 452000},
                           {'id': 11112, 'up': 450000, 'down': 462000},
                           {'id': 11113, 'up': 450000, 'down': 452000},
                           {'id': 11114, 'up': 450000, 'down': 462000}])