如何在上面的查询中展平聚合输出的JSON结果

时间:2018-04-12 12:54:40

标签: javascript node.js mongodb mongoose aggregation-framework

我正在尝试这个mongo聚合我得到了输出但我的所需输出没有得到任何人请建议我的问题

 const monthsEnum = {
            "_id": "year",
            "1": "January",
            "2": "February",
            "3": "March",
            "4": "April",
            "5": "May",
            "6": "June",
            "7": "July",
            "8": "August",
            "9": "September",
            "10": "October",
            "11": "November",
            "12": "December"
        };

        Light.aggregate([ 
            { "$match": {
                "CREATE_DATE": {
                    "$lte": new Date(),
                    "$gte": new Date(new Date().setDate(new Date().getDate()-120))
                }
            } },
            { "$group": {
                "_id": { 
                    "month": { "$month": "$CREATE_DATE" },
                    "year": { "$year": "$CREATE_DATE" }
                },
                "avgofozone": { "$avg": "$OZONE" }
            } },
            { "$group": {
                "_id": "$year",
                "avgs": {
                    "$push": {
                        "k": { "$substr": ["$month", 0, -1 ] },
                        "v": "$avgofozone"
                    }
                }
            } },
            { "$replaceRoot": { 
                "newRoot": { 
                    "$mergeObjects": [ 
                        { "$arrayToObject": "$avgs" }, 
                        "$$ROOT" 
                     ] 
                } 
            } },
            { "$project": { "avgs": 0 } }
        ], (err, data) => {
            console.log("naresh:" +JSON.stringify(data));
            const polute = Object.keys(data).reduce((p, c) => ({...p, monthsEnum[c]: data[c]}), {});
            res.json(polute);
        })
output:
[
    { 
        "zone_type": "avgofozone", 
        "year": 2018, 
        "February": 21.07777777777778, 
        "March": 17.8, 
        "January": 17.8 
    }
] 
MY expected output is: 
zone_type     year    February           March    January 
avgofozone    2018    21.07777777777778  17.8      17.8   

0 个答案:

没有答案