MongoDB Insert Documents

To insert documents in MongoDB you use insertOne for a single document and insertMany for several at once. These are the "C" (create) in CRUD. The examples below build the products collection used throughout this tutorial.

insertOne()

insertOne returns an acknowledgement and the _id of the new document.

use shop
db.products.insertOne({
  name: "Basmati Rice",
  category: "Grains",
  price: 12.5,
  stock: 120,
  tags: ["organic"]
})
{
  acknowledged: true,
  insertedId: ObjectId('6720a5d0c2b9e81d4f3a1b04')
}

insertMany()

Pass an array of documents. All of them are sent in one round trip, which is much faster than many single inserts.

db.products.insertMany([
  { name: "Green Tea", category: "Beverages", price: 6, stock: 300 },
  { name: "Olive Oil", category: "Oils", price: 18.75, stock: 45 },
  { name: "Dark Chocolate", category: "Snacks", price: 4.25, stock: 500 },
  { name: "Coffee Beans", category: "Beverages", price: 22, stock: 80 },
  { name: "Almonds", category: "Snacks", price: 15, stock: 60, tags: ["organic"] },
  { name: "Honey", category: "Sweeteners", price: 11.5, stock: 0 }
])
{
  acknowledged: true,
  insertedIds: {
    '0': ObjectId('6720a5e2c2b9e81d4f3a1b05'),
    '1': ObjectId('6720a5e2c2b9e81d4f3a1b06'),
    '2': ObjectId('6720a5e2c2b9e81d4f3a1b07'),
    '3': ObjectId('6720a5e2c2b9e81d4f3a1b08'),
    '4': ObjectId('6720a5e2c2b9e81d4f3a1b09'),
    '5': ObjectId('6720a5e2c2b9e81d4f3a1b0a')
  }
}

Custom _id Values

If you supply _id yourself, it must be unique. Inserting a duplicate causes an E11000 duplicate key error.

db.categories.insertOne({ _id: "grains", label: "Grains & Rice" })
db.categories.insertOne({ _id: "grains", label: "Duplicate" })
{ acknowledged: true, insertedId: 'grains' }
MongoServerError: E11000 duplicate key error collection: shop.categories index: _id_ dup key: { _id: "grains" }

Ordered vs Unordered Inserts

By default insertMany stops at the first error. With ordered: false it keeps going and reports every failure at the end, which is useful for bulk imports.

db.categories.insertMany(
  [{ _id: "oils" }, { _id: "grains" }, { _id: "snacks" }],
  { ordered: false }
)
MongoBulkWriteError: E11000 duplicate key error ... dup key: { _id: "grains" }
Result: { insertedCount: 2, ... }

Frequently asked questions

What is the difference between insertOne and insertMany?

insertOne adds a single document; insertMany adds an array of documents in one operation, which is faster for bulk data.

Does MongoDB create the collection automatically?

Yes. Inserting into a collection that does not exist creates it, along with the database if needed.

Is insert() still supported?

The old insert() method is deprecated. Use insertOne or insertMany in mongosh and all modern drivers.