【问题标题】:Group by day/month/week basis on the date range根据日期范围按天/月/周分组
【发布时间】:2016-09-01 19:13:48
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

    对于每周分组,运行以下管道,主要使用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" }
             }
        }
    ])
    

    【讨论】:

      猜你喜欢
      • 2011-03-02
      • 2010-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-09
      • 1970-01-01
      相关资源
      最近更新 更多