javascript - 我可以按日期查询 MongoDB ObjectId 吗?

我知道 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') } });

https://stackoverflow.com/questions/8749971/

相关文章:

database - 如何创建数据库的 MongoDB 转储?

windows - 如何在 Windows 上安装 mongoDB?

mongodb - Mongo Shell - 控制台/调试日志

ios - MongoDB 与 Firebase

mongodb - 什么时候应该使用 NoSQL 数据库而不是关系数据库?可以在同一个网站上使用两者

node.js - MongoDB/Mongoose 在特定日期查询?

mongodb - 如何在 MongoDB 中使用 Elasticsearch?

linux - BadValue 无效或未设置用户区域设置。请确保正确设置 LANG 和/或 LC_

javascript - 如何在 Mongoose 中排序?

mongodb - 当案例类包含 Scala 枚举时,如何使用 Rogue 和 MongoCaseC