Skip to the workspace
Pebellslearn by building
Collections & Methods  ›  Lesson

Inserting Documents

insert() and relevant 12 mininsertOne adds a single document and insertMany adds a list, each returning the new _id values, and an ordered insertMany stops at the first error while an unordered one carries on.

mongodb / Inserting Documents

Explore each scene at your own pace.

01 · The rule

The rule

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 _id values. Documents without an _id get an ObjectId.
  • A document whose _id already 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.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.