I have a query that is returning the total number of entries in a collection per year-month, grouped by a location.
This is returning data exactly as I need it if the location has results for the year-month in question.
However, is it possible to insert an entry for a month that does not have a result? For instance lets say if my $match has a date range of 01-2019
to 12-2019
. I would like to have all 12 entries for the month with a default of total: 0.
Truncated Schema :
{
branchId: { type: String, required: true },
orgId: { type: String, required: true },
stars: { type: Number, default: 0 },
reviewUpdatedAt: { type: Date, default: Date.now }
}
What I've tried:
[
{
$match: {
stars: { $exists: true, $gte: 1 },
orgId: '100003'
reviewUpdatedAt: { $gte: new Date(fromDate), $lte: new Date(toDate) }
}
},
{
$group: {
_id: {
date: {
$dateToString: {
format: "%m-%Y",
date: "$reviewUpdatedAt"
}
},
loc: "$branchId"
},
total: {
$sum: 1
}
}
},
{
$group: {
_id: "$_id.loc",
reviews: {
$push: {
total: "$total",
"date": "$_id.date"
}
}
}
}
]