objectid – 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:

    By default, creates a new unique identifier. The optional parameter oid can be an ObjectId, or any 12 or, in Python 2, any 12-character str.

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

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

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

    • Parameters

    The MongoDB documentation on ObjectIds.

    Changed in version 3.8: now implements the ObjectID specification version 0.2.

    • str(o)

      Get a hex encoded version of o.

      The following property always holds:

      This representation is useful for urls or other places where is inappropriate.

    • property binary

      12-byte binary representation of this ObjectId.

    • classmethod from_datetime(generation_time)

      Create a dummy ObjectId instance with a specific generation time.

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

      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:

      • Parameters

    • property generation_time

      A instance representing the time of generation for this ObjectId.

      The is timezone aware, and represents the generation time in UTC. It is precise to the second.

    • classmethod is_valid(oid)

      Checks if a oid string is valid or not.

      • Parameters

        • oid: the object id to validate

      New in version 2.3.