All academies
Roadmap
LEVEL 3 · CRUD OPERATIONS

Inserting Documents

10 min read

Use insertOne() for a single document and insertMany() for a batch. MongoDB adds an _id automatically if you don't supply one.

mongosh
db.products.insertOne({
  name: "Desk Mat", price: 19.99, stock: 50
})

db.products.insertMany([
  { name: "Cable Organizer", price: 8.99 },
  { name: "Phone Stand", price: 14.99 }
])

Write results

Inserts return an acknowledgement with the generated ids. If a document with the same _id already exists you get a duplicate key error (E11000) — _id is always unique.

mongosh
{
  acknowledged: true,
  insertedId: ObjectId("...")
}

Ordered vs unordered inserts

insertMany is ordered by default: it stops at the first error. Pass { ordered: false } to attempt every document and collect all errors — useful for bulk imports.

Try it yourself

db.products.insertOne({ name: "Desk Mat", price: 19.99, stock: 50 })
Run in Shell

Check your understanding

Q1.

What happens if you insert a document without an _id?

Q2.

The collection already has { _id: 1 }. What does this return?

code
db.items.insertOne({ _id: 1, name: 'dup' })
Q3.

insertMany stops at the first failing document by default.