Dávid Molnár
Dávid Molnár

Reputation: 11573

Who generates Mongodb _id (ObjectId) field's value?

If I insert a document, directly with a mongodb client or with Mongoose, who is responsible to generate the _id field's value? Is it happening inside the database engine or the clients do the work?

Upvotes: 0

Views: 33

Answers (1)

deceze
deceze

Reputation: 522125

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.

Note
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.

https://docs.mongodb.com/manual/core/document/index.html#the-id-field

Upvotes: 1

Related Questions