【问题标题】:How to support time interval when find documents from mongodb collection? [duplicate]从 mongodb 集合中查找文档时如何支持时间间隔? [复制]
【发布时间】:2013-03-07 20:33:13
【问题描述】:

我将以下文档保存在 mongodb 集合中。它们按升序排列。我只想在指定的时间间隔内获取一份文档。 (我正在使用 node.js 和 node-mongodb 驱动程序。)我应该如何实现它?

{"created_at":"2013-03-19T07:14:05Z"}
{"created_at":"2013-03-19T07:35:40Z"}
{"created_at":"2013-03-19T07:59:52Z"}
{"created_at":"2013-03-19T08:01:32Z"}
{"created_at":"2013-03-19T08:02:40Z"}
{"created_at":"2013-03-19T08:02:56Z"}
{"created_at":"2013-03-19T08:06:24Z"}
{"created_at":"2013-03-19T08:07:08Z"}
{"created_at":"2013-03-19T08:23:27Z"}
{"created_at":"2013-03-19T08:27:44Z"}
{"created_at":"2013-03-19T08:27:58Z"}
{"created_at":"2013-03-19T08:28:04Z"}
{"created_at":"2013-03-19T08:28:08Z"}
{"created_at":"2013-03-19T08:28:23Z"}

例如,如果时间间隔为 1 分钟,则预期结果如下。

{"created_at":"2013-03-19T07:14:05Z"}
{"created_at":"2013-03-19T07:35:40Z"}
{"created_at":"2013-03-19T07:59:52Z"}
{"created_at":"2013-03-19T08:01:32Z"}
{"created_at":"2013-03-19T08:02:40Z"}
{"created_at":"2013-03-19T08:06:24Z"}
{"created_at":"2013-03-19T08:07:08Z"}
{"created_at":"2013-03-19T08:23:27Z"}
{"created_at":"2013-03-19T08:27:44Z"}
{"created_at":"2013-03-19T08:28:04Z"}

以下文件不得退回。

{"created_at":"2013-03-19T08:02:56Z"}
{"created_at":"2013-03-19T08:27:58Z"}
{"created_at":"2013-03-19T08:28:08Z"}
{"created_at":"2013-03-19T08:28:23Z"}

谢谢,

杰弗里

【问题讨论】:

  • 没有。它们是不同的问题。
  • Map/Reduce 是您正在寻找的。​​span>
  • @Freakish,你能给个链接来描述细节吗?
  • 另一种考虑的方法是使用 MongoDB 的聚合框架:docs.mongodb.org/manual/applications/aggregation

标签: node.js mongodb node-mongodb-native


【解决方案1】:

Map/Reduce 正是您要找的。​​p>

这样想你的集合:你有 created_at 成为 ID 的文档。或者我应该说created_at 的那部分最多一分钟。所以例如这个函数将用于确定 ID:

var GenerateID = function(date) {
    return date.getFullYear() + "/" +
           date.getMonth() + "/" +
           date.getDate() + "." +
           date.getHours() + ":" +
           date.getMinutes();
};

所以这个函数将日期对象转换为一个字符串,包括年、月、日、小时和分钟。我们不关心秒数,因为您每分钟只需要一个对象。

现在您必须定义 map 和 reduce 函数。例如地图可能看起来像这样:

var map = function() {
    var key = GenerateID(this.created_at);
    emit(key, this);
};

并减少:

var reduce = function(key, values) {
    if (values.length) {
        return values[0];
    }
};

这里我们只返回我们拥有的第一个值(结合排序会给你想要的东西)。请注意,这是每个键,所以我们很好。

现在您必须在 Mongo 方面解雇这项工作。根据您的驱动程序,它可能如下所示:

db.collection.mapReduce(
    map,
    reduce,
    {
        out: { inline: 1 },
        query: // your range query
        sort: // by created_at
        scope: { GenerateID: GenerateID },
    }
)

这是官方 MongoDB 的 map/reduce 概览:

http://docs.mongodb.org/manual/applications/map-reduce/

【讨论】:

    猜你喜欢
    • 2014-02-15
    • 1970-01-01
    • 2015-08-19
    • 1970-01-01
    • 2021-03-17
    • 1970-01-01
    • 2018-07-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多