Inserting documents

MongoDB · Essentials · 7 min

Writing data is the first half of every CRUD feature you build.

insertOne(doc) adds one document and returns { acknowledged: true, insertedId: ... }. insertMany([docs]) adds several in one round trip and returns all the generated ids in insertedIds.

If the target collection doesn't exist it is created. If a document has no _id, one is generated. Inserting a document whose _id already exists (or that violates any other unique index) fails with a duplicate key error, code 11000.

insertMany is ordered by default: it inserts documents in sequence and stops at the first error, leaving earlier documents inserted. Pass { ordered: false } to let the server continue past failures and insert everything it can, which is also faster for bulk loads. Either way, a multi-document insert is not a transaction: a failure part way through does not roll back what was already written.

Each single-document write is atomic: other readers see the whole document or none of it, even when it contains nested arrays and objects. That is a key reason to model related data inside one document when it is read and written together.

For very large imports use mongoimport or bulkWrite, which mixes inserts, updates and deletes in one batch.

Example

use shop
db.products.insertOne({ _id: "PEN-01", name: "Pen", price: 1.5 })
// { acknowledged: true, insertedId: 'PEN-01' }

db.products.insertMany(
  [
    { _id: "PAD-07", name: "Notepad", price: 4.2 },
    { _id: "PEN-01", name: "Duplicate pen" },   // duplicate _id
    { _id: "INK-02", name: "Ink", price: 3 }
  ],
  { ordered: false }
)
// MongoBulkWriteError: E11000 duplicate key error ... dup key: { _id: "PEN-01" }
db.products.countDocuments()   // 3  (PAD-07 and INK-02 were still inserted)

Remember

  • insertOne returns insertedId; insertMany returns insertedIds
  • Duplicate _id or unique key: error 11000
  • ordered: true (default) stops at the first error; ordered: false continues
  • Single-document writes are atomic; multi-document inserts are not

Watch out for

  • Assuming a failed insertMany inserted nothing: documents before the error (or all valid ones, if unordered) are kept.

Check yourself

  1. An ordered insertMany of five documents hits a duplicate key on the third. How many are inserted?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: www.mongodb.com/docs/manual/tutorial/insert-documents/