Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

SOLVED: using mongo aggregation how to get the null month value

hema g:

I am trying this mongo aggregation get the last four months of data and calculate the each month of avarage value i got the output but how to get null month of value (ex: 3 months data are there one month data are not inserted for example April month value not inserted but to display "April":0 this my requrement any one please suggest me.


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

]
)
Actual Output:
{
"Mar" : 55.6,
"Jan" : 31.265,
"Feb" : 31.265,
"year" : 2018
}
Expected Output:
{
"Mar" : 55.6,
"Jan" : 31.265,
"Feb" : 31.265,
"Apr" :0
"year" : 2018,

}



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots


This post first appeared on Stack Solved, please read the originial post: here

Share the post

SOLVED: using mongo aggregation how to get the null month value

×

Subscribe to Stack Solved

Get updates delivered right to your inbox!

Thank you for your subscription

×