gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 11:12:04 24 4
gpt4 key购买 nike

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

关于javascript - 我可以按日期查询 MongoDB ObjectId 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8749971/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com