Skip to content

Instantly share code, notes, and snippets.

@adnan-i
Last active October 22, 2020 15:30
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save adnan-i/d82a956d67c153b5efc8 to your computer and use it in GitHub Desktop.
Save adnan-i/d82a956d67c153b5efc8 to your computer and use it in GitHub Desktop.
Mongoose aggregation for grouping users by month/year subscribed
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