如何使用MongoDB聚合来展平JSON结果?

时间:2018-04-17 12:19:22

标签: mongodb mongoose aggregation

聚合后,我得到一个不合预期的输出。有什么我能做的吗?

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" }
            } }

        ])

实际输出:

[
    { "avgofozone" : 21.07777777777778, "year" : 2018, "month" : 2 }
    { "avgofozone" : 17.8, "year" : 2018, "month" : 3 }
    { "avgofozone" : 17.8, "year" : 2018, "month" : 1 }
]

预期输出:

    [
        { 
            "zone_type": "avgofozone", 
            "year": 2018, 
            "February": 21.07777777777778, 
            "March": 17.8, 
            "January": 17.8 
        }
    ]

1 个答案:

答案 0 :(得分:0)

使用MongoDB> = v3.4.4,您可以将以下阶段添加到现有管道的末尾,以便为您进行转换:

{
    $addFields: {
        result: {
            $let: {
                vars: { "months": [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ], arr: { $objectToArray: "$$ROOT" } },
                in: {
                    "k" : { $arrayElemAt: [ "$$months" , { $subtract: [ { $arrayElemAt: [ "$$arr.v" , 2 ] }, 1 ] } ] },
                    "v" : { $arrayElemAt: [ "$$arr.v" , 0 ] }
                }
            }
        }
    }
}, {
    $group: {
        _id: "$year",
        result: { $push: "$result" },
    }
}, {
    $addFields: {
        "result": { $arrayToObject: "$result" },
    }
}, {
    $addFields: {
        "result.zonetype": "avgofozone",
        "result.year": "$_id"
    }
}, {
    $replaceRoot: {
        newRoot: "$result"
    }
}