nirvair
nirvair

Reputation: 4180

Group by day/month/week basis on the date range

This is in reference to this question.

This is my data set:

[
  {
    "rating": 4,
    "ceatedAt": ISODate("2016-08-08T15:32:41.262+0000")
  },
  {
    "rating": 3,
    "createdAt": ISODate("2016-08-08T15:32:41.262+0000")
  },
  {
    "rating": 3,
    "ceatedAt": ISODate("2016-07-01T15:32:41.262+0000")
  },
  {
    "rating": 5,
    "createdAt": ISODate("2016-07-01T15:32:41.262+0000")
  }
]

I want to be able to filter basis on week or month basis on the date range.

How would I do that in mongo?

This was the answer given for grouping by days.

db.collection.aggregate([
    { 
        "$project": {
            "formattedDate": { 
                "$dateToString": { "format": "%Y-%m-%d", "date": "$ceatedAt" } 
            },
            "createdAtMonth": { "$month": "$ceatedAt" },
            "rating": 1
        }
    },
    {
         "$group": {
             "_id": "$formattedDate",
             "average": { "$avg": "$rating" },
             "month": { "$first": "$createdAtMonth" },
         }
    }
])

Upvotes: 2

Views: 7345

Answers (1)

chridam
chridam

Reputation: 103425

For grouping on weekly basis, run the following pipeline which mainly uses the Date Aggregation Operators to extract the date parts:

db.collection.aggregate([
    { 
        "$project": {
            "createdAtWeek": { "$week": "$createdAt" },
            "createdAtMonth": { "$month": "$createdAt" },
            "rating": 1
        }
    },
    {
         "$group": {
             "_id": "$createdAtWeek",
             "average": { "$avg": "$rating" },
             "month": { "$first": "$createdAtMonth" }
         }
    }
])

and for monthly aggregates, interchange the $group key to use the created month field:

db.collection.aggregate([
    { 
        "$project": {
            "createdAtWeek": { "$week": "$createdAt" },
            "createdAtMonth": { "$month": "$createdAt" },
            "rating": 1
        }
    },
    {
         "$group": {
             "_id": "$createdAtMonth",
             "average": { "$avg": "$rating" },
             "week": { "$first": "$createdAtWeek" }
         }
    }
])

Upvotes: 4

Related Questions