【问题标题】:How do you group by date in mongo?你如何在mongo中按日期分组?
【发布时间】:2013-01-13 09:31:00
【问题描述】:

我有一堆文件:

{"timestamp" : 1304535236, "value" : 2}
{"timestamp" : 1304532236, "value" : 5}
{"timestamp" : 1304535647, "value" : 1}

timestamp 是一个 unix 时间戳。我想总结一下每天value 的总数。注意:可能有许多文档的时间戳落在同一天的不同时间。

如果我做一个普通的 mongo 组查询是每个时间戳的总和,因为它们都是唯一的,这是没有帮助的。

【问题讨论】:

    标签: mongodb pymongo mongodb-query


    【解决方案1】:

    您必须将您的 timestamp 值转换为 Date 对象,以便您可以按天分组。

    使用 Rachel 的答案作为起点(在 shell 中):

    db.test.group({
      keyf: function(doc) {
        var date = new Date(doc.timestamp*1000);
        var dateKey = (date.getMonth()+1) + "/" + 
                      date.getDate() + "/" + 
                      date.getFullYear();
        return {day: dateKey};
      },
      initial: {value: 0},
      reduce: function(curr, result) { result.value += curr.value; }
    });
    

    返回:

    [
      {
        "day": "5/4/2011",
        "value": 8
      }
    ]
    

    【讨论】:

    • shell 的答案和 Python 的问题
    猜你喜欢
    • 1970-01-01
    • 2018-12-12
    • 2017-10-22
    • 2023-03-14
    • 2013-11-15
    • 2021-09-08
    • 1970-01-01
    • 1970-01-01
    • 2012-01-23
    相关资源
    最近更新 更多