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

可紊 提交于 2019-12-02 02:09:20

问题


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" },
         }
    }
])

回答1:


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" }
         }
    }
])


来源:https://stackoverflow.com/questions/39269760/group-by-day-month-week-basis-on-the-date-range

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!