You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Inserting data is the first operation you will perform in MongoDB. The database provides two methods for inserting documents: insertOne for a single document and insertMany for multiple documents at once.
insertOne inserts a single document into a collection. If the collection does not exist, MongoDB creates it automatically.
db.users.insertOne({
name: "Alice",
email: "alice@example.com",
age: 28,
createdAt: new Date()
})
The method returns an object with an acknowledged flag and the insertedId of the new document.
{
acknowledged: true,
insertedId: ObjectId("64c3d4e5f6a7b8c9d0e1f002")
}
insertMany accepts an array of documents and inserts them all in a single round trip, which is far more efficient than calling insertOne in a loop.
db.products.insertMany([
{ name: "Keyboard", price: 49.99, stock: 150 },
{ name: "Mouse", price: 29.99, stock: 200 },
{ name: "Monitor", price: 299.00, stock: 40 }
])
The result includes an array of all insertedIds.
Every document must have a unique _id field. If you omit it, MongoDB generates an ObjectId automatically. You can also supply your own _id — any unique value works, including strings or integers:
db.countries.insertOne({ _id: "GB", name: "United Kingdom" })
By default, insertMany is ordered: if one document fails (for example, due to a duplicate _id), MongoDB stops processing the remaining documents. Pass { ordered: false } to continue inserting the rest even if some fail:
db.logs.insertMany(
[
{ _id: 1, msg: "start" },
{ _id: 1, msg: "duplicate" }, // will fail
{ _id: 2, msg: "end" }
],
{ ordered: false }
)
Write concern controls how many acknowledgements the driver waits for before confirming a write. The default { w: 1 } waits for the primary to acknowledge. For maximum durability you can use { w: "majority" } to wait for a majority of replica set members.
db.orders.insertOne(
{ item: "Widget", qty: 5 },
{ writeConcern: { w: "majority" } }
)
MongoDB handles complex structures natively:
db.articles.insertOne({
title: "NoSQL Explained",
author: { name: "Bob", email: "bob@example.com" },
tags: ["database", "nosql"],
sections: [
{ heading: "Introduction", wordCount: 320 },
{ heading: "Examples", wordCount: 640 }
]
})
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.