我可以按日期查询MongoDB ObjectId吗? [英] Can I query MongoDB ObjectId by date?
本文介绍了我可以按日期查询MongoDB ObjectId吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道ObjectIds包含它们的创建日期。有没有办法查询ObjectId的这个方面?
I know that ObjectIds contain the date they were created on. Is there a way to query this aspect of the ObjectId?
推荐答案
将时间戳弹出到ObjectIds中非常详细地介绍了基于ObjectId中嵌入的日期的查询。
Popping Timestamps into ObjectIds covers queries based on dates embedded in the ObjectId in great detail.
简要介绍JavaScript代码:
Briefly in JavaScript code:
// 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 ObjectId吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文