SyntaxStudy
Sign Up
MongoDB Beginner 1 min read

Insert Operations

MongoDB provides insertOne() to add a single document and insertMany() to add an array of documents in a single round trip. Both methods return a result object containing the inserted IDs. If any document in an insertMany() call fails validation, the default ordered behaviour stops at the first error; setting ordered: false continues inserting the remaining documents and collects all errors at the end. You can supply your own _id value of any type, but it must be unique within the collection. Attempting to insert a duplicate _id raises an E11000 duplicate key error. Insert operations are atomic at the single-document level; multi-document atomicity requires a transaction.
Example
// insertOne — returns { acknowledged: true, insertedId: ObjectId(...) }
const result = await db.collection('users').insertOne({
  name: "Carol",
  email: "carol@example.com",
  age: 28,
  createdAt: new Date()
})
console.log('Inserted:', result.insertedId)

// insertMany — bulk insert
const bulk = await db.collection('products').insertMany([
  { name: "Keyboard", price: 79.99, stock: 150 },
  { name: "Mouse",    price: 39.99, stock: 200 },
  { name: "Monitor",  price: 349.99, stock: 50 }
], { ordered: false })   // continue on error

console.log('Inserted count:', bulk.insertedCount)
console.log('IDs:', bulk.insertedIds)

// Custom _id (must be unique)
await db.collection('config').insertOne({
  _id: "appSettings",
  theme: "dark",
  language: "en"
})