MongoDB 查找今天的记录 [英] MongoDB find today's records

查看:55
本文介绍了MongoDB 查找今天的记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In Mongo shell, how would I filter records that have been added today (or on a specific date)? I have no specific field of the timestamp of new records, but I guess it can be restored from ObjectID.

推荐答案

我们可以使用 $where

we can use $where

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

要获取今天的文档,或者最好说是从最后一个午夜开始:

To get documents for today, or better say from last midnight:

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

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

of course it is much faster to have an indexed timestamp field or to follow the approach with the calculation of an ObjectID for the start date and compare _id against it, as _id is indexed too.

这篇关于MongoDB 查找今天的记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆