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.