Skip to content

Instantly share code, notes, and snippets.

@adnan-i
Last active October 22, 2020 15:30
Show Gist options
  • Select an option

  • Save adnan-i/d82a956d67c153b5efc8 to your computer and use it in GitHub Desktop.

Select an option

Save adnan-i/d82a956d67c153b5efc8 to your computer and use it in GitHub Desktop.

Revisions

  1. adnan-i revised this gist Feb 11, 2015. 1 changed file with 4 additions and 1 deletion.
    5 changes: 4 additions & 1 deletion mongoose-aggregate-by-month-year.js
    Original file line number Diff line number Diff line change
    @@ -1,11 +1,13 @@
    .aggregate([
    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: {
    @@ -18,6 +20,7 @@
    }
    },
    {
    /* sort descending (latest subscriptions first) */
    $sort: {
    '_id.year': -1,
    '_id.month': -1
  2. adnan-i created this gist Feb 11, 2015.
    29 changes: 29 additions & 0 deletions mongoose-aggregate-by-month-year.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,29 @@
    .aggregate([
    {
    $match: {
    /* "joined" is an ISODate field */
    'subscription.joined': {$ne: null}
    }
    },
    {
    $group: {
    _id: {
    year: {
    $year: '$subscription.joined'
    },
    month: {
    $month: '$subscription.joined'
    }
    },
    }
    },
    {
    $sort: {
    '_id.year': -1,
    '_id.month': -1
    }
    },
    {
    $limit: 100,
    },
    ])