Forked from adnan-i/mongoose-aggregate-by-month-year.js
Created
May 30, 2018 11:26
-
-
Save Quadriphobs1/5f9a6313630b4594f0f1f2481ebb6497 to your computer and use it in GitHub Desktop.
Mongoose aggregation for grouping users by month/year subscribed
This file contains hidden or 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