我想检索值插入特定日期使用mongodb的_id

I want to retrieve values inserted on particular date using _id of mongodb

本文关键字:mongodb id 日期 检索 插入      更新时间:2023-09-26

我想检索在特定日期插入的值。这是可能的使用mongodb"_id"字段吗?因为这包含嵌入式日期时间。我想在mongodb shell中检索值,而不是使用任何应用程序。

虽然ObjectId确实部分基于"时间戳",但通常这是一个"客户端"库操作,从ObjectId值中"提取"该日期。

你可以用JavaScript对 $where 求值,但它需要"扫描"整个集合,所以效率不高:

 db.collection.find(function() {
     return (
        ( this._id.getTimestamp().valueOf() - 
          this._id.getTimestamp().valueOf() % ( 1000 * 60 * 60 * 24 ) )
        == new Date("2014-07-14").valueOf() );
 })

这将比较ObjectId是否与提供的日期在同一天创建。其他日期数学或方法适用于其他间隔。