通过一个月的MongoDB结果汇总JSON格式

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

你好我与报告API将要在highcharts使用工作,我是新来的MongoDB。

下面是我的聚集查询(建议我修改):

db.product_sold.aggregate({

    $group: {
        _id: { year: { $year: "$solddate" }, month: { $month: "$solddate" }, productid: "$productid" },
        totalQty: { $sum: "$qty" }
    }

})

输出:

{ 
    "_id" : {
        "year" : NumberInt(2019), 
        "month" : NumberInt(2), 
        "productid" : "11"
    }, 
    "totalQty" : 6.0
}
// ----------------------------------------------
{ 
    "_id" : {
        "year" : NumberInt(2019), 
        "month" : NumberInt(2), 
        "productid" : "14"
    }, 
    "totalQty" : 7.0
}
// ----------------------------------------------
{ 
    "_id" : {
        "year" : NumberInt(2019), 
        "month" : NumberInt(1), 
        "productid" : "13"
    }, 
    "totalQty" : 3.0
}
// ----------------------------------------------
{ 
    "_id" : {
        "year" : NumberInt(2019), 
        "month" : NumberInt(2), 
        "productid" : "10"
    }, 
    "totalQty" : 6.0
}
// ----------------------------------------------
{ 
    "_id" : {
        "year" : NumberInt(2018), 
        "month" : NumberInt(2), 
        "productid" : "12"
    }, 
    "totalQty" : 5.0
}
// ----------------------------------------------
{ 
    "_id" : {
        "year" : NumberInt(2019), 
        "month" : NumberInt(2), 
        "productid" : "15"
    }, 
    "totalQty" : 8.0
}
// ----------------------------------------------
{ 
    "_id" : {
        "year" : NumberInt(2019), 
        "month" : NumberInt(1), 
        "productid" : "11"
    }, 
    "totalQty" : 2.0
}
// ----------------------------------------------

我理想中的输出是一样的东西:

status: 200,
msg: "SUCCESS"
data: [{
    1:[
        {
            "productid": 11,
            "totalQty": 3
        },
        {
            "productid": 12,
            "totalQty": 27
        }
    ],

    2:[
        {
            "productid": 11,
            "totalQty": 64
        },
        {
            "productid": 12,
            "totalQty": 10
        }
    ]   
}]

参考附集合的图像

enter image description here

有没有什么方法去实现它使用聚合或其他任何东西,否则我将不得不通过代码做手工?

mongodb aggregation-framework
1个回答
1
投票

您可以附加以下聚集阶段,您目前的管道:

db.product_sold.aggregate([
    // your current $group stage
    {
        $group: {
            _id: "$_id.month",
            docs: { $push: { productid: "$_id.productid", totalQty: "$totalQty" } }
        }
    },
    {
        $project: {
            _id: 0,
            k: { $toString: "$_id" },
            v: "$docs"
        }
    },
    {
        $group: {
            _id: null,
            data: { $push: "$$ROOT" }
        }
    },
    {
        $project: {
            _id: 0,
            data: { $arrayToObject: "$data" }
        }
    }
])

这里的想法是,你可以使用$group_id设置为null获取所有数据到单一的文件,然后使用$arrayToObject获得一个月号码作为关键,并在该月的值全部聚集。

© www.soinside.com 2019 - 2024. All rights reserved.