使用MongoDB的NodeJS嵌套组聚合

时间:2018-12-03 22:01:07

标签: node.js mongodb aggregation-framework

我有一个付款数据集,我希望将其分组以显示在报表表格的页面上。以下是数据:-

{
"_id": {
    "$oid": "5bed91bfbbcf4d0014ec3ab1"
},
"type": "Card",
"reason": "Deposit",
"item": "Dress",
"amount": 100,
},
{
"_id": {
    "$oid": "5bed91bfbbcf4d0014ec3ab2"
},
"type": "Cash",
"reason": "Deposit",
"item": "Dress",
"amount": 400,
},
{
"_id": {
    "$oid": "5bed91bfbbcf4d0014ec3ab3"
},
"type": "Cash",
"reason": "Deposit",
"item": "Dress",
"amount": 100,
},
{
"_id": {
    "$oid": "5bed91bfbbcf4d0014ec3ab4"
},
"type": "Cash",
"reason": "Full Balance",
"item": "Dress",
"amount": 200,
},
{
"_id": {
    "$oid": "5bed91bfbbcf4d0014ec3ab5"
},
"type": "Card",
"reason": "Full Balance",
"item": "Dress",
"amount": 300,
},
{
"_id": {
    "$oid": "5bed91bfbbcf4d0014ec3ab6"
},
"type": "Cash",
"reason": "Deposit",
"item": "Jacket",
"amount": 400,
},
{
"_id": {
    "$oid": "5bed91bfbbcf4d0014ec3ab7"
},
"type": "Card",
"reason": "Deposit",
"item": "Jacket",
"amount": 150,
},
{
"_id": {
    "$oid": "5bed91bfbbcf4d0014ec3ab8"
},
"type": "Cash",
"reason": "Full Balance",
"item": "Jacket",
"amount": 250,
},
{
"_id": {
    "$oid": "5bed91bfbbcf4d0014ec3ab9"
},
"type": "Card",
"reason": "Full Balance",
"item": "Jacket",
"amount": 350,
}

我可以按1个项目对数据进行分组,因此,例如,我可以按项目(礼服,夹克等)对金额进行分组和总计

我想按所有三个字段分组,这样会得到一个看起来像这样并且结构化的输出,以便可以在前端显示它们。

{
Dress: {
    reason: {
        "Deposit" : {
            type: {
                "Cash": 500 //Combination of 2 records for example
                "Card": 100
            }
        }
        "Full Balance" : {
            type: {
                "Cash": 200
                "Card": 300
            }
        }
    }
}
Jacket: {
    reason: {
        "Deposit" : {
            type: {
                "Cash": 400
                "Card": 150
            }
        }
        "Full Balance" : {
            type: {
                "Cash": 250
                "Card": 350
            }
        }
    }
}

我试图开始这一工作,但是我在努力使概念正确,以便能够生成正确的数据。显然,这不会产生正确的输出。

$group: {
        _id: {item: "$item"},
        totalAmount: {$sum: "$amount"}
    },
    $group: {
        _id: {item: "$_id.item"},
        total: {
            "$push": {
                type: {type: "$type"},
                amount: {$sum : "$amount"}
            }
        }

    }

感谢您的帮助。

0 个答案:

没有答案