使用mongo聚合如何获取null月值

时间:2018-04-23 07:14:53

标签: mongodb mongoose aggregation-framework

我正在尝试这个mongo聚合获取最后四个月的数据并计算每个月的平均值。我得到了输出,但是如何获得null月值,例如:3个月的数据是否有一个月没有插入数据例如4月份未插入数值而是显示“4月”:0?

db.collection.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"}
            } },
            { $sort:{ "year": -1 } },
            { $project: {
                year: '$_id.year',
                avgofozone: '$avgofozone',
                month: '$_id.month',_id:0
            } },
            {
        $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 ] } ] }, // the key will be the month index translated into the string representation
                        "v" : { $arrayElemAt: [ "$$arr.v" , 1 ] }
                    }
                }
            }
        }
    }, {
        $group: {
            _id: "$year", // group by year
            result: { $push: "$result" },
        }
    }, {
        $addFields: {
            "result": { $arrayToObject: "$result" },
        }
    }, {
        $addFields: {
            "result.year": "$_id"
        }
    }, {
        $replaceRoot: {
            newRoot: "$result"
        }
    }

      ]
       )

实际输出:

{
"Mar" : 55.6,
"Jan" : 31.265,
"Feb" : 31.265, 
"year" : 2018
}

预期产出:

{
 "Mar" : 55.6,
 "Jan" : 31.265,
 "Feb" : 31.265,
 "Apr" :0
 "year" : 2018,
}

0 个答案:

没有答案
相关问题