MCPcopy Index your code
hub / github.com/mongodb/mongo-python-driver / ObjectId

Class ObjectId

bson/objectid.py:48–258  ·  view source on GitHub ↗

A MongoDB ObjectId.

Source from the content-addressed store, hash-verified

46
47
48class ObjectId:
49 """A MongoDB ObjectId."""
50
51 _pid = os.getpid()
52
53 _inc = SystemRandom().randint(0, _MAX_COUNTER_VALUE)
54 _inc_lock = threading.Lock()
55
56 __random = _random_bytes()
57
58 __slots__ = ("__id",)
59
60 _type_marker = 7
61
62 def __init__(self, oid: Optional[Union[str, ObjectId, bytes]] = None) -> None:
63 """Initialize a new ObjectId.
64
65 An ObjectId is a 12-byte unique identifier consisting of:
66
67 - a 4-byte value representing the seconds since the Unix epoch,
68 - a 5-byte random value,
69 - a 3-byte counter, starting with a random value.
70
71 By default, ``ObjectId()`` creates a new unique identifier. The
72 optional parameter `oid` can be an :class:`ObjectId`, or any 12
73 :class:`bytes`.
74
75 For example, the 12 bytes b'foo-bar-quux' do not follow the ObjectId
76 specification but they are acceptable input::
77
78 >>> ObjectId(b'foo-bar-quux')
79 ObjectId('666f6f2d6261722d71757578')
80
81 `oid` can also be a :class:`str` of 24 hex digits::
82
83 >>> ObjectId('0123456789ab0123456789ab')
84 ObjectId('0123456789ab0123456789ab')
85
86 Raises :class:`~bson.errors.InvalidId` if `oid` is not 12 bytes nor
87 24 hex digits, or :class:`TypeError` if `oid` is not an accepted type.
88
89 :param oid: a valid ObjectId.
90
91 .. seealso:: The MongoDB documentation on `ObjectIds <http://dochub.mongodb.org/core/objectids>`_.
92
93 .. versionchanged:: 3.8
94 :class:`~bson.objectid.ObjectId` now implements the `ObjectID
95 specification version 0.2
96 <https://github.com/mongodb/specifications/blob/master/source/
97 objectid.rst>`_.
98 """
99 if oid is None:
100 # Generate a new value for this ObjectId.
101 with ObjectId._inc_lock:
102 inc = ObjectId._inc
103 ObjectId._inc = (inc + 1) % (_MAX_COUNTER_VALUE + 1)
104
105 # 4 bytes current time, 5 bytes random, 3 bytes inc.

Callers 15

__init__Method · 0.90
__init__Method · 0.90
test_objectidMethod · 0.90
test_dbrefMethod · 0.90
test_encode_subclassMethod · 0.90
oidFunction · 0.90
test_creationMethod · 0.90
test_unicodeMethod · 0.90
test_from_hexMethod · 0.90
test_repr_strMethod · 0.90
test_equalityMethod · 0.90

Calls 1

_random_bytesFunction · 0.85

Tested by 15

test_objectidMethod · 0.72
test_dbrefMethod · 0.72
test_encode_subclassMethod · 0.72
oidFunction · 0.72
test_creationMethod · 0.72
test_unicodeMethod · 0.72
test_from_hexMethod · 0.72
test_repr_strMethod · 0.72
test_equalityMethod · 0.72
test_generation_timeMethod · 0.72
test_picklingMethod · 0.72