【问题标题】:MongoDB Aggregate two fields from collection independently and countMongoDB独立地从集合中聚合两个字段并计数
【发布时间】:2021-12-16 07:12:01
【问题描述】:

我的 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
   }
}

希望有人可以帮助我执行此查询。我能做到的最接近的方法是将“向上”和“向下”放在“标签”下的数组中,但我希望它们彼此独立。

谢谢!

【问题讨论】:

    标签: mongodb pymongo


    【解决方案1】:

    我们可以$project$objectToArray 将向上和向下拆分为一个对象数组,然后$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}])
    

    【讨论】:

      猜你喜欢
      • 2021-06-26
      • 2019-05-16
      • 1970-01-01
      • 2015-05-15
      • 1970-01-01
      • 2017-07-13
      • 2020-06-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多