我能否通过日期查询MongoDB的ObjectId?

30 浏览
0 Comments

我能否通过日期查询MongoDB的ObjectId?

我知道ObjectIds包含它们被创建的日期。有没有一种方法来查询ObjectId的这个方面?

admin 更改状态以发布 2023年5月21日
0
0 Comments

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}}))

0
0 Comments

将时间戳嵌入ObjectId中的查询详细介绍了基于嵌入在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') } });

0