objectid -- Tools for working with MongoDB ObjectIds#
Tools for working with MongoDB ObjectIds.
- class bson.objectid.ObjectId(oid=None)#
Initialize a new ObjectId.
An ObjectId is a 12-byte unique identifier consisting of:
a 4-byte value representing the seconds since the Unix epoch,
a 5-byte random value,
a 3-byte counter, starting with a random value.
By default,
ObjectId()creates a new unique identifier. The optional parameter oid can be anObjectId, or any 12bytes.For example, the 12 bytes b'foo-bar-quux' do not follow the ObjectId specification but they are acceptable input:
>>> ObjectId(b'foo-bar-quux') ObjectId('666f6f2d6261722d71757578')
oid can also be a
strof 24 hex digits:>>> ObjectId('0123456789ab0123456789ab') ObjectId('0123456789ab0123456789ab')
Raises
InvalidIdif oid is not 12 bytes nor 24 hex digits, orTypeErrorif oid is not an accepted type.- Parameters:
oid (optional): a valid ObjectId.
参见
The MongoDB documentation on ObjectIds.
在 3.8 版本发生变更:
ObjectIdnow implements the ObjectID specification version 0.2.- str(o)
Get a hex encoded version of
ObjectIdo.The following property always holds:
>>> o = ObjectId() >>> o == ObjectId(str(o)) True
This representation is useful for urls or other places where
o.binaryis inappropriate.
- classmethod from_datetime(generation_time: datetime) ObjectId#
Create a dummy ObjectId instance with a specific generation time.
This method is useful for doing range queries on a field containing
ObjectIdinstances.警告
It is not safe to insert a document containing an ObjectId generated using this method. This method deliberately eliminates the uniqueness guarantee that ObjectIds generally provide. ObjectIds generated with this method should be used exclusively in queries.
generation_time will be converted to UTC. Naive datetime instances will be treated as though they already contain UTC.
An example using this helper to get documents where
"_id"was generated before January 1, 2010 would be:>>> gen_time = datetime.datetime(2010, 1, 1) >>> dummy_id = ObjectId.from_datetime(gen_time) >>> result = collection.find({"_id": {"$lt": dummy_id}})
- Parameters:
generation_time:
datetimeto be used as the generation time for the resulting ObjectId.
- property generation_time: datetime#
A
datetime.datetimeinstance representing the time of generation for thisObjectId.The
datetime.datetimeis timezone aware, and represents the generation time in UTC. It is precise to the second.