我可以按日期查询MongoDB ObjectId吗?
2022-08-30 02:09:23
我知道ObjectIds包含它们的创建日期。有没有办法查询 ObjectId 的这一方面?
我知道ObjectIds包含它们的创建日期。有没有办法查询 ObjectId 的这一方面?
在 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') } });
在 中,可以通过以下方式完成:pymongo
import datetime
from bson.objectid import ObjectId
mins = 15
gen_time = datetime.datetime.today() - datetime.timedelta(mins=mins)
dummy_id = ObjectId.from_datetime(gen_time)
result = list(db.coll.find({"_id": {"$gte": dummy_id}}))