Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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