Beginner MongoDB

Inserting Documents in MongoDB

Master insertOne() and insertMany() to add documents to your MongoDB collections efficiently.

5 min read Tutorial

Inserting Documents

MongoDB stores data as BSON documents (binary JSON). To add data to a collection, you use insertOne() for a single document or insertMany() for multiple documents at once. If the collection does not exist, MongoDB creates it automatically on the first insert.

insertOne()

The insertOne() method inserts a single document into a collection and returns an acknowledgment with the generated _id:

db.products.insertOne({
  name: "Mechanical Keyboard",
  price: 149.99,
  category: "electronics",
  tags: ["gaming", "rgb", "wireless"],
  specs: {
    switches: "Cherry MX Blue",
    layout: "TKL"
  },
  createdAt: new Date()
})

// Result:
// {
//   acknowledged: true,
//   insertedId: ObjectId("64a7b2c3d4e5f6a7b8c9d0e1")
// }

insertMany()

Use insertMany() to insert an array of documents in a single operation. This is significantly faster than calling insertOne() in a loop:

db.products.insertMany([
  {
    name: "USB-C Hub",
    price: 49.99,
    category: "accessories",
    inStock: true
  },
  {
    name: "Monitor Stand",
    price: 89.99,
    category: "accessories",
    inStock: false
  },
  {
    name: "Webcam HD",
    price: 79.99,
    category: "electronics",
    inStock: true
  }
])

The _id Field

Every document in MongoDB must have a unique _id field. If you do not provide one, MongoDB automatically generates an ObjectId. You can also supply your own:

// Custom _id
db.products.insertOne({
  _id: "PROD-001",
  name: "Desk Lamp",
  price: 34.99
})

// MongoDB will NOT generate an ObjectId when you provide _id

Ordered vs Unordered Inserts

By default, insertMany() performs ordered inserts -- it stops on the first error. Set ordered: false to continue inserting remaining documents even if some fail:

// Unordered insert: continues even if one document fails
db.products.insertMany(
  [
    { _id: 1, name: "Item A" },
    { _id: 1, name: "Item B" },  // duplicate _id, will fail
    { _id: 2, name: "Item C" }   // still gets inserted
  ],
  { ordered: false }
)

Key Takeaways

  • Use insertOne() for a single document and insertMany() for bulk inserts.
  • MongoDB auto-generates an _id (ObjectId) unless you provide one.
  • Collections are created implicitly on first insert.
  • Use ordered: false for fault-tolerant bulk inserts.

Try this query in UnifySQL

Write, optimize, and collaborate on MongoDB queries with AI assistance.

Start Free