Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 70 ยท CRUD: create and read

Inserting Documents

Learn how to insert documents in MongoDB: insertOne, insertMany, generated _id values, ordered vs unordered inserts, duplicate key errors and write results.

Everything in a MongoDB database starts with an insert. You give the server one document or a list of documents, it stores them in a collection, and it tells you whether that worked. There is no CREATE TABLE step first: if the collection does not exist yet, the first insert creates it.

This lesson covers the two insert methods, what the server adds on its own (the _id field), what the result object tells you, and how errors behave when a batch contains a bad document. If you have not met _id yet, _id and ObjectId explains it in depth.

MongoDB itself cannot run on this site. The mongosh listings are real commands and are read-only. The runnable examples use the small JavaScript practice engine from The Practice Engine Used in This Tutorial: it stores documents in an array and imitates the insert behavior described here, including the error text. It is a stand-in, not a database.

Two ways to insert

insertOne One document, one result.
insertMany An array of documents in one round trip.
_id Added for you if you leave it out.
1 / 2

insertOne

insertOne takes a single document. In mongosh, you call it on a collection through the db object:

JavaScript
use shop

db.products.insertOne({
  name: "Desk Lamp",
  price: 24.5,
  tags: ["lighting", "office"],
  stock: { warehouse: 40, store: 6 }
})

The server answers with a small result document. The two fields you will use are acknowledged (the write was confirmed by the server) and insertedId (the _id of the new document):

JavaScript
{
  acknowledged: true,
  insertedId: ObjectId('65f1a2b3c4d5e6f708000001')
}

The exact ObjectId value is different on every run. A document can hold nested documents and arrays, as the stock and tags fields show. Documents, JSON and Field Types covers what a document may contain.

The generated _id

Every document in a collection needs a unique _id. If you do not supply one, the driver creates an ObjectId and adds it as the first field of the document before sending it. Notice that this normally happens in your application's driver, not on the server, so you can read the new id from the result without a second query.

You may also supply your own _id, and it can be any type except an array: a number, a string, a UUID or a whole subdocument. That is useful when your data already has a natural key, such as a product SKU. The price is that you are now responsible for uniqueness, and an id that is already taken makes the insert fail, as you will see below.

The first TryIt

The practice engine mirrors this behavior. Run the example, then change the documents and run it again. Try adding your own _id to the second document, or inserting a document with an id that is already used.

JS insertOne with and without an _id

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The error is a duplicate key error, code 11000. The message names the collection, the index (_id_ is the automatic unique index on _id) and the value that collided. Code 11000 is the number to check for in your application when you need to react to "this already exists".

insertMany

When you have several documents, insertMany takes an array and sends them together. This is much faster than calling insertOne in a loop, because it needs far fewer network round trips and the server can process the batch efficiently.

JavaScript
db.products.insertMany([
  { name: "Desk Lamp", price: 24.5 },
  { name: "Notebook", price: 3.2 },
  { name: "Stapler", price: 8 }
])

The result lists the generated ids by their position in the array you sent:

JavaScript
{
  acknowledged: true,
  insertedIds: {
    '0': ObjectId('65f1a2b3c4d5e6f708000001'),
    '1': ObjectId('65f1a2b3c4d5e6f708000002'),
    '2': ObjectId('65f1a2b3c4d5e6f708000003')
  }
}

Drivers split very large arrays into several batches for you, because the server limits how many documents and how many bytes go into one message. You can pass a long list, and the driver takes care of the splitting. If you are loading a huge amount of data, Bulk Writes describes the more general tool.

Ordered and unordered inserts

By default, insertMany is ordered. The server inserts the documents in the order you gave them, and when one fails it stops. Documents that were already inserted stay in the collection: an insert batch is not a transaction.

Pass { ordered: false } to make the server try every document. Failures do not stop the rest, and at the end you get one error that lists all of them. Unordered inserts can also run faster, because the server is free to process documents in any order.

JavaScript
db.products.insertMany(
  [
    { _id: 1, name: "Desk Lamp" },
    { _id: 1, name: "Duplicate lamp" },
    { _id: 2, name: "Notebook" }
  ],
  { ordered: false }
)

With ordered: false, documents 0 and 2 are inserted and document 1 is reported as a failure. With the default ordered: true, only document 0 is inserted and document 2 is never tried. Pick ordered inserts when later documents depend on earlier ones, and unordered inserts when the documents are independent and you want as many as possible to succeed.

When a batch fails, the error object tells you which documents were rejected. In the Node.js driver the error exposes a writeErrors list, in which every entry has the index of the failed document in your array, its error code and a message. It also carries the count of documents that did get inserted. You will see this driver in Using MongoDB from Node.js.

JS Ordered vs unordered insertMany

Press Run (or Ctrl + Enter) to see the console output here.

No output.

In the ordered run, the third and fourth documents were never tried, because the second one failed first. In the unordered run, every valid document is stored and only the duplicate is reported.

The legacy insert() method

Older tutorials and scripts use db.collection.insert(), a single method that accepts either one document or an array:

JavaScript
db.products.insert({ name: "Desk Lamp", price: 24 })                   // one document
db.products.insert([{ name: "Notebook" }, { name: "Pen" }])            // several documents
db.products.insert({ name: "Mug" }, { writeConcern: { w: "majority" }, ordered: true })

insert() is deprecated and, in current drivers and mongosh, no longer the recommended path. Its weakness is the result: it returns a WriteResult (for one document) or a BulkWriteResult (for an array), so your code has to check what came back. insertOne and insertMany have one clear result shape each (insertedId and insertedIds), which is why new code should use them. You can still meet insert() in old shell scripts, so know that its options map onto the modern ones: writeConcern sets how many servers must confirm the write, and ordered decides whether a failure stops the batch (see the section above). If the document has no _id, the server adds one, exactly as for insertOne.

Good habits when inserting

  • Let the driver make _id unless you have a real natural key. Generated ids are unique without coordination, even across many application servers.
  • Check the result (or catch the error) instead of assuming success. For critical data, a write concern controls how many servers must confirm the write: Read and Write Concerns covers it.
  • Insert in batches when loading lots of data, and choose ordered: false when documents are independent.
  • Keep documents modest. A single document may not exceed 16 MB, and you rarely want to get anywhere near that.
  • Validate before you insert. MongoDB is flexible about structure, so a typo in a field name is stored happily. Schema Validation shows how to have the server reject bad documents.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. You call insertOne without an _id field. What happens?

    The driver adds an ObjectId as _id before sending the document. Every stored document has an _id, and there is no automatic integer counter.
  2. 2. An ordered insertMany of five documents fails on the third one with a duplicate key error. Which documents are in the collection afterwards?

    An ordered insert stops at the first error, and the documents inserted before it stay. Inserts are not transactional unless you use a multi-document transaction.
  3. 3. Which option makes insertMany keep going after a failed document?

    ordered: false lets the server attempt every document and report all failures together. bypassDocumentValidation only skips schema validation.
  4. 4. What does error code 11000 mean?

    11000 is the duplicate key error. It is raised by any unique index, and the automatic index on _id is one of them.

Summary

  • insertOne stores a single document and insertMany stores an array of them; the collection is created on the first insert.
  • If you omit _id, the driver generates an ObjectId and places it first; you can supply your own unique _id of almost any type.
  • The result reports acknowledged and the inserted id or ids (insertedId, insertedIds).
  • Reusing an _id raises a duplicate key error with code 11000 and the message names the colliding value.
  • Batches are ordered by default and stop at the first error; { ordered: false } continues and reports every failure. Documents inserted before an error are kept.

Next, read the data back with Finding Documents.