Last active
October 22, 2020 15:30
-
-
Save adnan-i/d82a956d67c153b5efc8 to your computer and use it in GitHub Desktop.
Mongoose aggregation for grouping users by month/year subscribed
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
User.aggregate([ | |
{ | |
/* Filter out users who have not yet subscribed */ | |
$match: { | |
/* "joined" is an ISODate field */ | |
'subscription.joined': {$ne: null} | |
} | |
}, | |
{ | |
/* group by year and month of the subscription event */ | |
$group: { | |
_id: { | |
year: { | |
$year: '$subscription.joined' | |
}, | |
month: { | |
$month: '$subscription.joined' | |
} | |
}, | |
} | |
}, | |
{ | |
/* sort descending (latest subscriptions first) */ | |
$sort: { | |
'_id.year': -1, | |
'_id.month': -1 | |
} | |
}, | |
{ | |
$limit: 100, | |
}, | |
]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment