Mongodb(或猫鼬)获取当前日期小于其自身间隔的文档

Mongodb (or mongoose) get documents with a current date less than its own interval

文档结构(与此问题无关的字段已删除):

{
    _id: ObjectId,
    lastDate: Date,
    interval: Integer, // in seconds
    mode: String
}

我正在寻找的查询类似于:

{
    lastDate: {
        $lt: new Date() - $interval
    },
    mode: {
        $in: ['collect', 'debug']
    }
}

因此,查询将获取 lastDate 小于当前 date/time 减去其自身间隔的所有文档。也只获取模式设置为收集或调试的文档。

这可以通过基本查询来完成,还是我需要使用聚合或 mapReduce?

我找到了解决方案,但我不确定它是否是性能最好的解决方案。

有效的查询:

{
    $where: "this.lastDate < new Date() - this.interval",
    mode: {
        $in: ['collect', 'debug']
    }
}

使用 the $where operation

Use the $where operator to pass either a string containing a JavaScript expression or a full JavaScript function to the query system. The $where provides greater flexibility, but requires that the database processes the JavaScript expression or function for each document in the collection. Reference the document in the JavaScript expression or function using either this or obj.

从数学上讲,您的条件是

lastDate < current_time - interval

相当于

lastDate + interval < current_time

因此,不是(或除了)存储 lastDateinterval,而是存储它们的总和。总和可以存储为自纪元以来的秒数或日期 - 您可以在客户端代码中选择对您最方便的内容。