WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

MongoDB · Basic · question 5 of 100

What is the role of the _id field in a MongoDB document, and how is it generated?

📕 Buy this interview preparation book: 100 MongoDB questions & answers — PDF + EPUB for $5

In MongoDB, the _id field is a unique identifier assigned to each document in a collection. It serves as the primary key for the document, and is required for all documents.

The _id field can be assigned manually by the user, or it can be automatically generated by MongoDB. If the user does not provide a value for _id when inserting a document, MongoDB will create a unique ObjectId and assign it to the document as the _id field.

An ObjectId is a 12-byte value consisting of a time stamp, a machine identifier, a process id, and a counter. This provides a high degree of uniqueness even across distributed systems, making it a reliable choice for generating _id values.

Here’s an example of inserting a document into a MongoDB collection with a manually-assigned _id field:

db.users.insertOne({_id: "john_doe", name: "John Doe", age: 42})

And here’s an example of inserting a document with an automatically-generated ObjectId:

db.users.insertOne({name: "Jane Smith", age: 35})

In the second example, MongoDB will generate an ObjectId for the _id field of the document.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic MongoDB interview — then scores it.
📞 Practice MongoDB — free 15 min
📕 Buy this interview preparation book: 100 MongoDB questions & answers — PDF + EPUB for $5

All 100 MongoDB questions · All topics