The example in this article describes how Python generates MongoDB Objectid based on time. Share to everyone for your reference. The specific analysis is as follows:
MongoDB _id for the Objectid type, Objectid contains timestamp information, so that we save the data when there is no need to record a separate add time, if you need to query according to time, we can change the time to query the Objectid, and then through _ ID field query, because the MongoDB _id is the primary key, query efficiency is very high. The following function shows how to convert time to Objectid, and the function can also specify the offset of time, such as how many days ago.
Copy Code code as follows:
def object_id_from_datetime (From_datetime=none,span_days=0,span_hours=0,span_minutes=0,span_seconds=0,span_ Weeks=0):
"" To generate a Objectid manually based on time, this ID is not used as storage
If not from_datetime:
From_datetime = Datetime.datetime.now ()
From_datetime = From_datetime + Datetime.timedelta (days=span_days,hours=span_hours,minutes=span_minutes,weeks=span _weeks)
Return Objectid.from_datetime (Generation_time=from_datetime)
I hope this article will help you with your Python programming.