Skip to content

Inserting documents

Inserting is the gentlest operation in MongoDB: you hand the database a document, it stores it, and it tells you what it stored. There is no schema to define first and no table columns to line up against — if the document is valid JSON-like data, it goes in. That freedom is exactly why a tiny bit of discipline around the _id field pays off, which is the one piece of bookkeeping every insert involves.

We will keep building our imaginary library. Each member is a document, and in this lesson we add them to a collection called members.

insertOne takes exactly one document and stores it. If you do not supply an _id, MongoDB generates one for you as an ObjectId — a 12-byte value that is unique across the collection and even encodes the creation time. That generated id is the primary key of the document.

db.members.insertOne({ name: "Grace", joined: 2024, fines: 0 })

The acknowledgement tells you the operation succeeded and hands back the id that was assigned. In the shell it looks like this:

{ "acknowledged": true, "insertedId": "65f0b3d4e4b0a1c2e4b0a1d0" }

And the document now sitting in the collection looks like this — the _id is the only thing you did not type yourself:

{
"_id": "65f0b3d4e4b0a1c2e4b0a1d0",
"name": "Grace",
"joined": 2024,
"fines": 0
}

In Compass: open the members collection, click the green ADD DATA button, choose Insert Document, paste your JSON without an _id, and Compass fills the id in for you when you save.

When you have a batch of documents, insertMany sends them in one round trip instead of one call per document. You pass an array, and you get back the ids of everything that was inserted, keyed by their position in the array.

db.members.insertMany([
{ name: "Linus", joined: 2023, fines: 2 },
{ name: "Margaret", joined: 2025, fines: 0 },
{ name: "Edsger", joined: 2022, fines: 5 }
])

The acknowledgement maps each array index to the id that was generated for it:

{
"acknowledged": true,
"insertedIds": {
"0": "65f0b3d4e4b0a1c2e4b0a1d1",
"1": "65f0b3d4e4b0a1c2e4b0a1d2",
"2": "65f0b3d4e4b0a1c2e4b0a1d3"
}
}
  • You may supply your own _id (a string, number, or any value) instead of letting MongoDB generate an ObjectId — but it must be unique. Inserting a document whose _id already exists fails with a duplicate key error.
  • insertMany is ordered by default: it stops at the first failing document, so documents after a duplicate-id error never get inserted. Pass an unordered option to keep going past failures and insert every document that does not collide.
  • Because there is no schema, two documents in the same collection can have completely different fields. Inserting is forgiving; that is a feature, not a bug — just stay consistent on purpose.
If you insert a document without an _id field, what happens?
By default, what does an ordered insertMany do when one document has a duplicate _id?
What does the acknowledgement of insertMany contain?