Every document in MongoDB needs a unique _id. Using custom _id values lets you control this unique identifier instead of letting MongoDB create one automatically.
Custom _id values in MongoDB
Start learning this pattern below
Jump into concepts and practice - no test required
db.collection.insertOne({ _id: customValue, otherField: value })The _id field can be any unique value: string, number, or object.
If you don't provide _id, MongoDB creates a unique ObjectId automatically.
_id "user123".db.users.insertOne({ _id: "user123", name: "Alice" })_id 1001.db.products.insertOne({ _id: 1001, name: "Pen", price: 1.5 })_id.db.orders.insertOne({ _id: { orderNumber: 500, region: "US" }, total: 250 })This example inserts a product with a custom string _id "sku123" and then finds it using that _id.
use shop // Insert a product with custom _id db.products.insertOne({ _id: "sku123", name: "Notebook", price: 3.99 }) // Find the product by _id db.products.find({ _id: "sku123" })
Custom _id values must be unique in the collection; duplicates cause errors.
Using meaningful _id values can make queries faster since _id is always indexed.
Every MongoDB document needs a unique _id.
You can set your own _id value instead of using the default ObjectId.
Custom _id helps with meaningful IDs and faster lookups.
Practice
What is the purpose of the _id field in a MongoDB document?
Solution
Step 1: Understand the role of
The_idin MongoDB_idfield is a unique identifier for each document in a collection, ensuring no two documents share the same_id.Step 2: Compare with other options
Other options describe unrelated fields or metadata, not the unique identifier role.Final Answer:
It uniquely identifies each document in a collection. -> Option AQuick Check:
_id= unique document ID [OK]
_id means unique ID for each document [OK]- Thinking
_idstores creation date - Confusing
_idwith user data fields - Assuming
_idis optional
Which of the following is the correct way to insert a document with a custom _id value in MongoDB?
db.users.insertOne({ _id: 123, name: "Alice" })Solution
Step 1: Identify correct
The_idfield usage_idfield must be named exactly_idto set a custom ID. db.users.insertOne({ _id: 123, name: "Alice" }) uses_id: 123correctly.Step 2: Check other options for errors
db.users.insertOne({ id: 123, name: "Alice" }) usesidinstead of_id. db.users.insertOne({ _id: "name", name: "Alice" }) uses a string"name"which is valid but less meaningful here. db.users.insertOne({ _id: ObjectId(), name: "Alice" }) uses default ObjectId, not custom.Final Answer:
db.users.insertOne({ _id: 123, name: "Alice" }) -> Option BQuick Check:
Custom_idneeds exact field name [OK]
_id for custom IDs [OK]- Using
idinstead of_id - Confusing ObjectId() with custom values
- Using invalid types for
_id
Given the following documents inserted into a collection:
<pre>db.products.insertMany([ { _id: "p1", name: "Pen" }, { _id: "p2", name: "Pencil" }, { _id: "p3", name: "Eraser" } ]) What willdb.products.find({ _id: "p2" }).toArray() return?Solution
Step 1: Understand the query filter
The query searches for a document with_idequal to "p2".Step 2: Match the document in the collection
The document with_id: "p2"has the name "Pencil" and exists in the collection.Final Answer:
[{ _id: "p2", name: "Pencil" }] -> Option AQuick Check:
Query by custom_idreturns matching document [OK]
_id returns matching document [OK]- Expecting multiple documents returned
- Confusing
_idwith other fields - Assuming query returns error for string
_id
Consider this insertion attempt:
db.orders.insertOne({ _id: 101, item: "Book" })
db.orders.insertOne({ _id: 101, item: "Notebook" })What error will occur and why?
Solution
Step 1: Check uniqueness requirement of
The_id_idfield must be unique in a collection. Both documents use_id: 101.Step 2: Identify the error caused by duplicate
Inserting the second document with the same_id_idcauses a DuplicateKeyError.Final Answer:
DuplicateKeyError because_idmust be unique. -> Option DQuick Check:
Duplicate_idcauses insertion error [OK]
_id [OK]- Thinking
_idcan repeat - Confusing syntax error with duplicate key error
- Assuming
_idmust be string only
You want to store user profiles with custom _id values based on their email addresses to speed up lookups. Which approach is best?
// Option A
{ _id: ObjectId(), email: "user@example.com", name: "User" }
// Option B
{ _id: "user@example.com", name: "User" }
// Option C
{ email: "user@example.com", name: "User" }
// Option D
{ _id: UUID(), email: "user@example.com", name: "User" }Solution
Step 1: Understand the goal of custom
The goal is to speed up lookups by using email as the unique identifier._idStep 2: Evaluate options for best fit
Setting_idto the email string enables direct lookup using the email as_id, making queries fast. Using default ObjectId or UUID with separate email requires additional indexing. Omitting_idis invalid since it is mandatory.Final Answer:
Set_idto the email string for direct lookup. -> Option CQuick Check:
Custom_idas email speeds queries [OK]
_id for fast direct lookups [OK]- Ignoring
_iduniqueness requirement - Using default IDs when custom IDs help
- Not indexing email for fast queries
