In MongoDB, each document stored in a collection requires a unique _id
field that acts as a primary key. If an inserted document omits the _id
field, the MongoDB driver automatically generates an ObjectId
for the _id
field.
The _id field has the following behavior and constraints:
- By default, MongoDB creates a unique index on the
_id
field during the creation of a collection. - The
_id
field is always the first field in the documents. If the server receives a document that does not have the _id
field first, then the server will move the field to the beginning. - The
_id
field may contain values of any BSON data type, other than an array.
While storing values for _id
, we can follow these options: Use an ObjectId, Use a natural unique identifier, Generate an auto-incrementing number, Generate a UUID in our application code.
Most MongoDB driver clients will include the _id
field and generate an ObjectId
before sending the insert operation to MongoDB; however, if the client sends a document without an _id
field, the mongod
will add the _id
field and generate the ObjectId
.