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. Theoptional parameter oid can be an ObjectId, or any 12bytes or, in Python 2, any 12-character str.

For example, the 12 bytes b’foo-bar-quux’ do not follow the ObjectIdspecification but they are acceptable input:

  1. >>> ObjectId(b'foo-bar-quux')
  2. ObjectId('666f6f2d6261722d71757578')

oid can also be a unicode or str of 24 hex digits:

  1. >>> ObjectId('0123456789ab0123456789ab')
  2. ObjectId('0123456789ab0123456789ab')
  3. >>>
  4. >>> # A u-prefixed unicode literal:
  5. >>> ObjectId(u'0123456789ab0123456789ab')
  6. ObjectId('0123456789ab0123456789ab')

Raises InvalidId if oid is not 12 bytes nor24 hex digits, or TypeError if oid is not an accepted type.

Parameters:

  • oid (optional): a valid ObjectId.

See also

The MongoDB documentation on

objectids

Changed in version 3.8: ObjectId now implements the ObjectIDspecification version 0.2.

  • str(o)
  • Get a hex encoded version of ObjectIdo.

The following property always holds:

  1. >>> o = ObjectId()
  2. >>> o == ObjectId(str(o))
  3. True

This representation is useful for urls or other places whereo.binary is inappropriate.

  • binary
  • 12-byte binary representation of this ObjectId.

  • classmethod fromdatetime(_generation_time)

  • Create a dummy ObjectId instance with a specific generation time.

This method is useful for doing range queries on a fieldcontaining ObjectId instances.

Warning

It is not safe to insert a document containing an ObjectIdgenerated using this method. This method deliberatelyeliminates the uniqueness guarantee that ObjectIdsgenerally provide. ObjectIds generated with this methodshould be used exclusively in queries.

generation_time will be converted to UTC. Naive datetimeinstances 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:

  1. >>> gen_time = datetime.datetime(2010, 1, 1)
  2. >>> dummy_id = ObjectId.from_datetime(gen_time)
  3. >>> result = collection.find({"_id": {"$lt": dummy_id}})

Parameters:

  1. - _generation_time_: [<code>datetime</code>](https://docs.python.org/3/library/datetime.html#datetime.datetime) to be usedas the generation time for the resulting ObjectId.

The datetime.datetime is timezone aware, andrepresents the generation time in UTC. It is precise to thesecond.

  • classmethod isvalid(_oid)
  • Checks if a oid string is valid or not.

Parameters:

  1. - _oid_: the object id to validate

New in version 2.3.