I have a MongoDB query that groups by 5min windows based on date and returns count (which is the total number of documents in that 5min window using count: { $sum: 1 }
).
I'd like to have the query also return a count of 0 for a particular 5min window if no documents exist in that group. However currently, looks like only groups with a positive count are returned.
Current Query:
const cursor = await collection.aggregate([
{ $sort : { time : 1 } },
{
$match: {
$and: [
{selector: string },
{time: {$gte: timestamp }}
]
}
},
{
$group: {
_id: {
$subtract: [
{ $subtract: [ "$time", 0 ] },
{ $mod: [
{ $subtract: [ "$time", 0 ] },
1000 * 60 * 5
]}
],
},
count: { $sum: 1 }
}
}
])
Expected response: timestamp with count of documents including sum 0
{ _id: 1525162000000, count: 314 }
{ _id: 1523144100000, count: 0 }
{ _id: 1512155500000, count: 54 }
Thanks in advance!
Disclaimer: I do not recommend doing this on the server side (so inside MongoDB) but rather handle that case on the client side.
That said, here is a generic solution to your problem which should be easily adaptable to your specific case.
Imagine you have the following documents (or output from an aggregation pipeline as in your example):
The following pipeline will create empty buckets (so documents with a count of 0 for the "gap" values that are missing from the range of values in the
category
field - in this case the number 2):The output of the above query will be: