mongodb聚合计数不同的字段和另一个字段的组

时间:2017-05-18 08:12:50

标签: mongodb aggregation-framework

假设我有一个如下所示的数据:

[
    {
        "id": "ch_19yARNHDsLEzoG2t2hxHvpw3",
        "currency": "usd",
        "customer": "cus_1",
        "amount": 1200, 
    },{
        "id": "ch_19yASNHDsLEzoG2tfbFOFswm",
        "currency": "jpy",
        "customer": "cus_1",
        "amount": 1800, 
    },{
        "id": "ch_19yXtXHDsLEzoG2t7P5vTkoD",
        "currency": "php",
        "customer": "cus_2",
        "amount": 1500, 
    },{
        "id": "cus_Aa11MnL8d6Vui6",
        "currency": "usd",
        "customer": "cus_3",
        "amount": 2000, 
    },{
        "id": "cus_AXjwOn1zKAyIPN",
        "currency": "php",
        "customer": "cus_4",
        "amount": 500, 
    },
]

首先,我希望得到完全不同的客户。然后,我想按货币对数据进行分组,得到总和并将其作为数组存储在字段中。这就是它的样子。

{
    "total_customers": 4,
    "gross": [
        {
            "currency": "usd",
            amount: 3200
        },{
            "currency": "jpy",
            amount: 1800
        },{
            "currency": "php",
            amount: 2000
        }
    ]
}

1 个答案:

答案 0 :(得分:0)

首先,您可能在示例中遇到错误,如果您需要为每个客户每种货币计算每笔金额,那么在“php”货币中您应该有2000.

我相信这个任务有很多更优雅的解决方案(可能应该在两个查询中完成,但如果你想要一个在一起),我可以分享我的快速:

db.getCollection('trips').aggregate([
    { $group: { _id: "$customer", save:{$push:{currency:"$currency", amount:"$amount"}}}},
    { $group: { _id: null, count: {$sum:1}, save:{$push:"$save"}}},
    { $unwind : "$save" },
    { $unwind : "$save" },
    { $group: {_id:{currency:"$save.currency",total_customers:"$count"}, gross:{ $sum:"$save.amount"}}},
    { $group: {_id:"$_id.total_customers", gross:{ $push:{currency:"$_id.currency",amount:"$gross"}}}},
    { $project: {_id:0, total_customers:"$_id", gross:"$gross"}}
])

结果:

{
    "gross" : [ 
        {
            "currency" : "jpy",
            "amount" : 1800
        }, 
        {
            "currency" : "usd",
            "amount" : 3200
        }, 
        {
            "currency" : "php",
            "amount" : 2000
        }
    ],
    "total_customers" : 4.0
}

P.S。我不是说它是最好的/最佳的:))