我知道objectid包含它们创建的日期.有没有办法查询ObjectId的这一方面?

推荐答案

Popping Timestamps into ObjectIds详细介绍了基于ObjectId中嵌入的日期的查询.

简而言之,在JavaScript代码中:

/* This function returns an ObjectId embedded with a given datetime */
/* Accepts both Date object and string input */

function objectIdWithTimestamp(timestamp) {
    /* Convert string date to Date object (otherwise assume timestamp is a date) */
    if (typeof(timestamp) == 'string') {
        timestamp = new Date(timestamp);
    }

    /* Convert date object to hex seconds since Unix epoch */
    var hexSeconds = Math.floor(timestamp/1000).toString(16);

    /* Create an ObjectId with that hex timestamp */
    var constructedObjectId = ObjectId(hexSeconds + "0000000000000000");

    return constructedObjectId
}


/* Find all documents created after midnight on May 25th, 1980 */
db.mycollection.find({ _id: { $gt: objectIdWithTimestamp('1980/05/25') } });

Mongodb相关问答推荐

通过mongoDB中的查找从管道中删除被阻止的用户

我可以在BSON中使用代理字段吗?

如何对嵌套在另一个数组中的数组中的字段执行查找?

MongoDB Aggregate 根据时间进行多重分组

如何判断 MongoDB 的两个数组中是否存在值?

Mongo:投影不影响布尔值

使用名为 Object 键的 uuid 创建 mongodb 文档

为什么 local.oplog.rs 上每隔几分钟的活动就会锁定 mongo 客户端

在 Heroku 上使用 Node 读取、写入和存储 JSON

使用 ObjectId.GenerateNewId() 还是离开 MongoDB 创建一个?

django 和 mongodb 是否使迁移成为过go ?

在 Mongoose 中填写所有必填字段

MongoDb 数据库与集合

如何在 MongoDB 中删除此弃用警告,为什么会这样?

如何使用 mgo 从 golang 中的 mongodb 集合中 Select 所有记录

错误:需要数据和盐参数

MongoDB聚合框架的索引优化

MongoDB InsertMany 与 BulkWrite

聚合 $lookup 匹配管道中文档的总大小超过最大文档大小

如何在 Windows 上停止 mongodb 服务器?