按月结果的MongoDB聚合JSON格式

时间:2019-02-04 18:58:44

标签: mongodb aggregation-framework

您好,我正在使用将在highcharts中使用的报告api,而我是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

是否可以使用聚合或其他方法来实现它,否则我将不得不通过代码手动完成它?

1 个答案:

答案 0 :(得分: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" }
        }
    }
])

这里的想法是,您可以使用_id设置为null的{​​{3}}来将所有数据收集到单个文档中,然后使用$group来获取月份数作为键,并将该月的所有总计作为值。