【问题标题】:MongoDB - aggregate $group by every seven days from a dateMongoDB - 从某个日期起每 7 天聚合一次 $group
【发布时间】:2017-11-30 18:06:12
【问题描述】:

假设集合中有任意数量的文档,其结构如下:

{ 
    "_id" : "1", 
    "totalUsers" : NumberInt(10000), 
    "iosUsers" : NumberInt(5000), 
    "androidUsers" : NumberInt(5000), 
    "creationTime" : ISODate("2017-12-04T06:14:21.529+0000")
},
{ 
    "_id" : "2", 
    "totalUsers" : NumberInt(12000), 
    "iosUsers" : NumberInt(6000), 
    "androidUsers" : NumberInt(6000), 
    "creationTime" : ISODate("2017-12-04T06:14:21.529+0000")
},
{ 
    "_id" : "3", 
    "totalUsers" : NumberInt(14000), 
    "iosUsers" : NumberInt(7000), 
    "androidUsers" : NumberInt(7000), 
    "creationTime" : ISODate("2017-12-04T06:14:21.529+0000")
}

并且想要编写一个查询,返回两个给定日期之间的结果(即:startDateendDate),然后每 7 天对结果进行分组:

db.collection.aggregate(
  { $match: {$gte: startDate, $lte: endDate } },
  { $group: { _id: { --- every seven days from endDate --- } }
)

我该怎么做?

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework


    【解决方案1】:

    首先获取边界

    var boundries = [];
    vat sd= ISODate("2017-10-18T20:41:33.602+0000"),ed=ISODate("2017-11-22T12:41:36.348+0000");
    boundries.push(sd);
    
    var i = sd;
    
    while(i<=ed){
        //push ISODate(i + 7 days) in boundries
    }
    
    //also push ISODate(ed+1day) because upper bound is exclusive
    
    //use $bucket aggregation
    db.collection.aggregate({$match:{creationTime:{$gte:stDate,$lte:endDate}}},{
    $bucket:{
        groupBy: "$creationTime", 
        boundaries:boundries ,
    }
    
    })
    

    【讨论】:

      猜你喜欢
      • 2023-02-16
      • 2020-06-13
      • 1970-01-01
      • 2021-08-07
      • 2016-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多