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

后端 未结 1 1486
长发绾君心
长发绾君心 2021-01-22 03:16

This is in reference to this question.

This is my data set:

[
  {
    \"rating\": 4,
    \"ceatedAt\": ISODate(\"2016-08-08T15:32:41.262+0000\")
  },
  {         


        
1条回答
  •  一向
    一向 (楼主)
    2021-01-22 03:53

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

    0 讨论(0)
提交回复
热议问题