按日期/月/周分组日期范围

时间:2016-09-01 11:00:29

标签: mongodb date group-by aggregation-framework mongodb-aggregation

这是参考此question

这是我的数据集:

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

我希望能够在日期范围内按周或按月过滤基础。

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

这是按天分组的答案。

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 个答案:

答案 0 :(得分:2)

对于每周分组,运行以下管道,主要使用Date Aggregation Operators来提取日期部分:

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

并针对每月汇总,互换 $group 键以使用创建的月份字段:

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