MongoDB 查找今天的记录

Bot*_*ond 6 mongodb

在 Mongo shell 中,如何过滤今天(或特定日期)添加的记录?我没有新记录时间戳的特定字段,但我想它可以从 ObjectID 恢复。

tha*_*isp 8

我们可以用 $where

db.collection.find(
   { $where: "this._id.getTimestamp() >= ISODate('2017-02-25')" }
)
Run Code Online (Sandbox Code Playgroud)

要获取今天的文件,或者最好从昨天午夜开始说:

db.collection.find( { $where: function() { 
    today = new Date(); //
    today.setHours(0,0,0,0);
    return (this._id.getTimestamp() >= today)
} } );
Run Code Online (Sandbox Code Playgroud)

当然,拥有索引时间戳字段或遵循计算开始日期的 ObjectID 并将 _id 与其进行比较的方法要快得多,因为 _id 也被索引。