按日期范围按日/月/周分组 [英] Group by day/month/week basis on the date range

查看:197
本文介绍了按日期范围按日/月/周分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是参考这个问题

这是我的数据集:

[
  {
    "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.

我如何在mongo中做到这一点?

How would I do that in mongo?

这是给天分组的答案。 p>

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


推荐答案

为了每周进行分组,请运行以下管道,主要使用 Date Aggregation Operators 来提取日期部分s:

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

并为每月汇总,将 $ group 键可使用创建的月份字段:

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

这篇关于按日期范围按日/月/周分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆