0
0
MongoDBquery~5 mins

Auto-generated _id behavior in MongoDB - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the purpose of the _id field in MongoDB documents?
The _id field uniquely identifies each document in a MongoDB collection. It acts like a primary key to ensure no two documents have the same identifier.
Click to reveal answer
beginner
What happens if you insert a document into MongoDB without specifying an _id field?
MongoDB automatically generates a unique _id of type ObjectId for the document before inserting it.
Click to reveal answer
intermediate
Describe the structure of the default ObjectId generated for the _id field.
The ObjectId is a 12-byte value consisting of: a 4-byte timestamp (seconds since epoch), a 5-byte random value, and a 3-byte incrementing counter. This ensures uniqueness and time ordering.
Click to reveal answer
beginner
Can you insert a document with a custom _id value in MongoDB?
Yes, you can specify your own _id value when inserting a document. MongoDB will use it as the unique identifier instead of generating one.
Click to reveal answer
beginner
What error occurs if you try to insert two documents with the same _id value?
MongoDB throws a duplicate key error because _id must be unique within a collection.
Click to reveal answer
What type does MongoDB use by default for the auto-generated _id field?
AInteger
BString
CUUID
DObjectId
If you insert a document without an _id, what does MongoDB do?
AGenerates a unique <code>_id</code> automatically
BRejects the insert
CInserts with a null <code>_id</code>
DAsks the user to provide <code>_id</code>
Which part of the ObjectId encodes the creation time?
ALast 3 bytes
BFirst 4 bytes
CMiddle 5 bytes
DEntire 12 bytes
Can you use a string as a custom _id in MongoDB?
AOnly integers are allowed
BNo, only ObjectId is allowed
CYes, any unique value can be used
DOnly UUIDs are allowed
What happens if you try to insert two documents with the same _id?
AMongoDB throws a duplicate key error
BThe second insert overwrites the first
CMongoDB ignores the second insert
DBoth documents are inserted
Explain how MongoDB generates the _id field automatically when it is not provided.
Think about the parts that make ObjectId unique and time-ordered.
You got /5 concepts.
    Describe what happens if you insert a document with a custom _id that already exists in the collection.
    Consider MongoDB's rule about unique identifiers.
    You got /3 concepts.