By default new ObjectIDs are generated by the client/driver (although they can also be generated on the server if the client does not provide an
_id). In most cases the driver generates the ObjectID (for
_id) and adds this to the document representation before sending the server request.
Example from PyMongo documentation on Inserting a Document:
When a document is inserted a special key,
"_id" , is automatically added if the document doesn’t already contain an
"_id" key. The value of
"_id" must be unique across the collection.
The “automatically added” mention is referring to the driver adding the
_id to your document. This allows the driver to provide the
_id for a document without waiting for a round-trip to the server to fetch a generated
_id. You can also use that
_id to prepare multiple related documents in a transaction.
ObjectIDs are generally monotonically increasing because of the leading timestamp prefix, but do not strictly reflect insertion order. The granularity of the timestamp is in seconds, so multiple ObjectIDs generated within the same second do not have predictable ordering. The client can also generate ObjectIDs well before the request is sent to the server, or be subject to clock skew for the timestamp component.
Random bytes change for each call to generate a new ObjectID. This provides some differentiation for ObjectIDs that may be generated concurrently on different application servers.
Since ObjectIDs are typically generated on the client, the deployment topology does not factor into the ordering of ObjectIDs. Even if the ObjectIDs are generated on the server, multiple ObjectIDs generated in the same second will not have a predictable ordering.
For a use case requiring strict insertion order you could use a capped collection to provide a guarantee that results queried in natural order will reflect insertion order. However, capped collections have many associated restrictions in order to achieve this guarantee. They are FIFO (FIrst-In First-Out) collections with a maximum file size and do not allow direct removal or changing document size in updates.
If capped collections aren’t a suitable solution, you will have to find an alternative approach to ensure generation of unique monotonically increasing identifiers that reflect insertion order and suit your use case.
For an overview of common approaches and their associated benefits & drawbacks, see: Generating Globally Unique Identifiers for Use with MongoDB.