C100DBA · Question #45
What is the output of following two commands in MongoDB: db. posts. insert({n_id":l}) db.posts.insert({"_id":l})
The correct answer is C. This will throw a duplicate key error. Option C is correct because MongoDB enforces a unique index on the _id field by default. Both commands attempt to insert a document with _id: 1, so the second insert throws E11000 duplicate key error - MongoDB rejects it entirely, no partial success. Why the distractors are…
Question
What is the output of following two commands in MongoDB: db. posts. insert({n_id":l}) db.posts.insert({"_id":l})
Options
- ATwo documents will be inserted with _id as 1
- BMongoDB will automatically increment the _id of the second document as 2
- CThis will throw a duplicate key error
- DIt will insert two documents and throw a warning to the user
How the community answered
(27 responses)- A4% (1)
- B4% (1)
- C93% (25)
Explanation
Option C is correct because MongoDB enforces a unique index on the _id field by default. Both commands attempt to insert a document with _id: 1, so the second insert throws E11000 duplicate key error - MongoDB rejects it entirely, no partial success.
Why the distractors are wrong:
- A is wrong because
_iduniqueness is non-negotiable; MongoDB will never store two documents sharing the same_id. - B is wrong because MongoDB only auto-generates an
_id(as an ObjectId) when you omit it - it never silently increments an explicitly provided value. - D is wrong because MongoDB does not have a "warn and continue" mode for unique index violations; it raises a hard error and the second document is not written.
Memory tip: Treat _id exactly like a SQL primary key - duplicate primary keys always throw errors, never warnings or auto-fixes.
Topics
Community Discussion
No community discussion yet for this question.