How to insert documents into MongoDB collections
insertOne, insertMany, ordered vs unordered inserts, auto-generated _id, insert error handling, bulk write basics
insertOne and insertMany
MongoDB provides two core insert methods. insertOne adds a single document and returns an object containing the auto-generated or provided insertedId. insertMany accepts an array of documents and returns the count and all inserted IDs. Both methods are asynchronous and should always be awaited.
// insertOne — returns { acknowledged: true, insertedId: ObjectId }
const result = await db.collection('products').insertOne({
name: 'Mechanical Keyboard',
price: 79.99,
category: 'peripherals',
inStock: true,
createdAt: new Date()
})
console.log(result.insertedId) // ObjectId('...')
// insertMany — insert an array of documents
const res = await db.collection('products').insertMany([
{ name: 'Mouse', price: 29.99, inStock: true },
{ name: 'Monitor', price: 299.99, inStock: false }
])
console.log(res.insertedCount) // 2
console.log(res.insertedIds) // { '0': ObjectId, '1': ObjectId }Ordered vs unordered inserts
By default, insertMany runs in ordered mode — it stops at the first error and skips remaining documents. Pass { ordered: false } to continue inserting remaining documents even after a failure in one of them, maximizing successful writes in a batch.
await db.collection('events').insertMany(docs, { ordered: false })
// Partial success: check insertedCount vs docs.lengthIf you supply a duplicate _id, MongoDB throws error code 11000. Omit _id entirely to let MongoDB auto-generate an ObjectId. Insert operations do not validate document structure unless a JSON Schema validator is attached to the collection at the database level.
