although there are similar questions here, how to find / count documents in a specific week range, I was unable to find out, how to match / count documents from last X weeks. Consider this query:
db.getCollection('post').aggregate([
{
$match: {
createdDate: {'$gte': new Date(new Date() - 7 * 60 * 60 * 24 * 1000)},
}
},
{
$group: {
_id: {$week: '$createdDate'},
count: {$sum: 1}
}
}
])
This query counts documents from the last 7 days and groups the count by the week number - but the result actually contain two fileds: the number of of documents from the current week and the number of documents from last week starting from the day which is current day - 7 days.
Example - query starting on Wednesday:
- Last 7 days previous week: [Thu, Fri, Sat, Sun] | current week: [ Mon, Tue, Wed]
- last week previous week: [Mon, Tue, Wed, Thu, Fri, Sat, Sun] | current week: [ ]
The query should return right result not matter if started on first day of a week or last day of a week. Also year change has to be taken in account - last week of December has week number 52, first week of January week number 1.
Other potential issues may result from weeks without any related documents. You just can't group documents from the last 21 Days by the week number and use $sort
and $limit
, because weeks without any related document wouldn't appear in the grouping.