Skip to content

MongoDB Insert Document

MongoDB provides multiple methods for inserting documents, allowing you to insert single or multiple documents.

Insert Single Document

insertOne() Method

javascript
db.collection.insertOne(document, options)

Basic Example

javascript
// Insert single document
db.users.insertOne({
  name: "John",
  age: 25,
  email: "john@example.com",
  createdAt: new Date()
})

Return Result

json
{
  "acknowledged": true,
  "insertedId": ObjectId("65a1b2c3d4e5f6g7h8i9j0k1")
}

Insert Multiple Documents

insertMany() Method

javascript
db.collection.insertMany(documents, options)

Basic Example

javascript
// Insert multiple documents
db.users.insertMany([
  {
    name: "John",
    age: 25,
    email: "john@example.com"
  },
  {
    name: "Jane",
    age: 30,
    email: "jane@example.com"
  },
  {
    name: "Bob",
    age: 28,
    email: "bob@example.com"
  }
])

Return Result

json
{
  "acknowledged": true,
  "insertedIds": [
    ObjectId("65a1b2c3d4e5f6g7h8i9j0k1"),
    ObjectId("65a1b2c3d4e5f6g7h8i9j0k2"),
    ObjectId("65a1b2c3d4e5f6g7h8i9j0k3")
  ]
}

Insert Options

ordered Option

javascript
// ordered: true (default) - stop on error
db.users.insertMany([
  { name: "A" },
  { name: "B" },
  { _id: 1, name: "C" },
  { _id: 1, name: "D" }  // Duplicate _id, will error and stop
], { ordered: true })

// ordered: false - continue on error
db.users.insertMany([
  { name: "A" },
  { name: "B" },
  { _id: 1, name: "C" },
  { _id: 1, name: "D" }  // Duplicate _id, errors but continues
], { ordered: false })

writeConcern Option

javascript
db.users.insertOne(
  { name: "John", age: 25 },
  {
    writeConcern: {
      w: "majority",      // Wait for majority nodes
      j: true,            // Write to journal
      wtimeout: 5000      // Timeout in milliseconds
    }
  }
)

Specifying _id Field

Custom _id

javascript
// Use string as _id
db.users.insertOne({
  _id: "user_001",
  name: "John",
  age: 25
})

// Use number as _id
db.products.insertOne({
  _id: 1001,
  name: "iPhone",
  price: 999
})

Compound _id

javascript
db.orders.insertOne({
  _id: {
    orderNo: "ORD2024001",
    sequence: 1
  },
  customer: "John",
  amount: 1000
})

Inserting Nested Documents

Basic Nesting

javascript
db.users.insertOne({
  name: "John",
  address: {
    street: "123 Main St",
    city: "New York",
    zipCode: "10001"
  },
  contacts: {
    phone: "555-0123",
    email: "john@example.com"
  }
})

Array Nesting

javascript
db.products.insertOne({
  name: "iPhone 15 Pro",
  colors: ["Black", "White", "Blue"],
  specs: [
    { type: "Storage", value: "256GB" },
    { type: "Screen", value: "6.1 inches" }
  ],
  tags: ["phone", "apple", "flagship"]
})

Inserting Dates and Times

Current Time

javascript
db.events.insertOne({
  name: "User Registration",
  timestamp: new Date(),           // Current UTC time
  localTime: new Date().toLocaleString()
})

Specified Time

javascript
db.events.insertOne({
  name: "Meeting",
  startTime: new Date("2024-01-20T10:00:00Z"),
  endTime: ISODate("2024-01-20T12:00:00Z")
})

Inserting Binary Data

BinData

javascript
db.files.insertOne({
  filename: "document.pdf",
  contentType: "application/pdf",
  data: BinData(0, "base64encodedstring...")
})

Bulk Insert Best Practices

Batch Insert

javascript
// Batch insert for large amounts of data
var batchSize = 1000
var totalDocs = 10000

for (var i = 0; i < totalDocs; i += batchSize) {
  var batch = []
  for (var j = 0; j < batchSize && (i + j) < totalDocs; j++) {
    batch.push({
      index: i + j,
      data: "Sample data " + (i + j),
      createdAt: new Date()
    })
  }
  db.bulkdata.insertMany(batch)
  print("Inserted " + (i + batch.length) + " documents")
}

Error Handling

javascript
try {
  var result = db.users.insertMany([
    { name: "John" },
    { name: "Jane" },
    { _id: "existing_id", name: "Bob" }  // Potentially duplicate _id
  ], { ordered: false })
  
  print("Successfully inserted:", result.insertedIds.length)
} catch (e) {
  print("Insert error:", e)
  if (e.writeErrors) {
    e.writeErrors.forEach(function(err) {
      print("Error document index:", err.index)
      print("Error message:", err.errmsg)
    })
  }
}

Insert Validation

Check Insert Result

javascript
var result = db.users.insertOne({
  name: "John",
  age: 25
})

if (result.acknowledged) {
  print("Insert successful, ID:", result.insertedId)
} else {
  print("Insert failed")
}

Summary

Key points for inserting documents:

  • insertOne() for single document insertion
  • insertMany() for more efficient batch insertion
  • Auto-generates ObjectId when _id not specified
  • Use ordered: false for better batch insert fault tolerance
  • Large batches should be inserted in chunks

In the next chapter, we will learn about MongoDB Query Document.

Content is for learning and research only.