MongoDB — Inserting Documents
Learn how to write single and bulk insert operations using insertOne() and insertMany(). Understand ordered vs unordered bulk options and write concerns.
1Inserting a Single Document with insertOne()
The db.collection.insertOne() method adds a single document to a collection:
insertOne Example
db.users.insertOne({
name: "Balaji Nayak",
email: "balaji@ourcompiler.com",
role: "admin",
createdAt: new Date()
});
// Returns:
// {
// acknowledged: true,
// insertedId: ObjectId("65d8f1e2a9b3c4d5e6f7a8b9")
// }
2Inserting Multiple Documents with insertMany()
Use db.collection.insertMany() to insert an array of documents in a single network round-trip:
insertMany Example
db.products.insertMany([
{ title: "Keyboard", price: 49.99, stock: 100 },
{ title: "Mouse", price: 24.99, stock: 150 },
{ title: "Monitor", price: 199.99, stock: 45 }
]);
3Ordered vs Unordered Inserts
By default, insertMany() executes in ordered mode ({ ordered: true }). If an error occurs on the 2nd document, execution halts immediately and remaining documents are skipped.
In unordered mode ({ ordered: false }), MongoDB continues inserting remaining valid documents even if one fails due to duplicate key errors!
Unordered Bulk Insert
db.users.insertMany(
[
{ _id: 1, name: "Alice" },
{ _id: 1, name: "Duplicate Alice" }, // Fails (duplicate key)
{ _id: 2, name: "Bob" } // Inserted successfully!
],
{ ordered: false }
);