Inserting Documents
A supplier sends a list of new books. You could loop and insert them one by one, but that means a round trip per book and messy error handling. mongosh gives you two methods, one for a single document and one for a batch, and knowing how the batch behaves on errors saves real headaches.
The rule
insertOne for one, insertMany for a list; ordered batches stop at the first error.
db.newArrivals.insertOne({ title: "Kindred", author: "Octavia E. Butler", year: 1979, price: 6.75, stock: 4 })
// { acknowledged: true, insertedId: ObjectId("...") }
db.newArrivals.insertMany([
{ title: "Beloved", author: "Toni Morrison", year: 1987 },
{ title: "Matilda", author: "Roald Dahl", year: 1988 }
])
// { acknowledged: true, insertedIds: { '0': ObjectId("..."), '1': ObjectId("...") } }- The result tells you the new
_idvalues. Documents without an_idget an ObjectId. - A document whose
_idalready exists fails with an E11000 duplicate key error. - insertMany is ordered by default: it inserts in order and stops at the first failure. Pass
{ ordered: false }to try every document and report all failures at the end. - Successful inserts are never rolled back by a later failure in the batch.
The old insert() method still appears in tutorials, but it is deprecated in mongosh; use the two above.
The shortcut
For a batch with a bad document, find the first failure, then ask: ordered or not? Ordered keeps everything before it. Unordered keeps everything except it.
Spot the failure
Books 1 and 2 both carry
_id: 101. Book 1 claims it; book 2 will fail with E11000.
The trap: re-running the whole batch after a failure. The books that succeeded now clash with themselves and fail as duplicates.
Drills
Answer fast — trust the rule.
Which method adds a single document?
An ordered insertMany of 5 documents fails on the 3rd. How many are inserted?
The same batch runs with { ordered: false }. How many are inserted?
What error does inserting an existing _id raise?
Remember
- insertOne for one, insertMany for a list; ordered batches stop at the first error.
- Shortcut: find the first failure; ordered keeps what came before, unordered keeps all but the failures.
- Trap: nothing is rolled back, so never blindly re-run a batch that half succeeded.
