使用MongoDB将多个聚合查询合并为一个

问题描述 投票:1回答:1

我正在使用这三个查询来具有以下列的python数据帧格式:“日期”,“业务2的百分比”,“业务3的百分比”。 (每天都有从业务2和业务3获利的百分比)。

query_business2 = collection.aggregate( [
        {
          '$match': {'Business': 2}      
        },
        {
                '$group': {
                        '_id': '$Date',
                        'stab2': {'$sum': '$Money'}
                }
        },
        {
                '$sort': {'_id': 1}
        }
        ])
query_business3 = collection.aggregate([
        {
                '$match': {'Business':3}
        },
        {
                '$group': {
                        '_id': '$Date',
                        'stab3': {'$sum': '$Money'}
                        }
        },
        {
                '$sort': {'_id': 1}
        }
        ])
query_total = collection.aggregate([
        {
                '$group': {
                        '_id': '$Date',
                        'total': {'$sum': '$Money'}
                        }
        },
        {
                '$sort': {'_id': 1}
        }
        ])

为了更快,我想将这三个查询合并为一个。我尝试使用“ $ or”,但对于无法兑现的字典却无效。有更好的方法吗?在查询之后,可能无需使用熊猫就可以直接制作数据框格式,并且可以直接计算每个业务相对于总收入的百分比。谢谢您的帮助

mongodb aggregation-framework pymongo
1个回答
1
投票

感谢prasad_答案是:

query_business = collection.aggregate([
        {
            '$group':{
                    '_id': '$Date',
                    'total_2': {'$sum' : {'$cond': [{'$eq': ['$Business', 2]}, '$Money', 0]}},
                    'total_3': {'$sum' : {'$cond': [{'$eq': ['$Business', 3]}, '$Money', 0]}},
                    'total': {'$sum': '$Money'},
                    }
        },
        {
            '$match': {'$and': [{ 'total_2': {'$gt': 0}}, {'total': {'$gt': 0}},{'total_3':{'$gt':0}}]}     
        },
        {
            '$addFields':{
                    'part_2': { "$multiply": [ { "$divide": ["$total_2","$total"] }, 100 ] },
                    'part_3': { "$multiply": [{'$divide': ['$total_3','$total']}, 100]}
                    }
        }
        ])
© www.soinside.com 2019 - 2024. All rights reserved.