MongoDB Insert
Learn how to add documents to MongoDB collections
➕ Inserting Documents
Inserting documents in MongoDB means adding new data records to collections. You can insert single documents with insertOne() or multiple documents at once using insertMany() method for efficient data storage.
// Insert a single document
db.users.insertOne({ name: "Alice", age: 25 })
// Insert multiple documents
db.users.insertMany([
{ name: "Bob", age: 30 },
{ name: "Carol", age: 28 }
])
Insert Methods
MongoDB provides several methods to insert documents into collections. Each method serves different purposes depending on whether you're adding one or multiple documents at a time.
insertOne()
Insert a single document
db.users.insertOne({...})
insertMany()
Insert multiple documents
db.users.insertMany([...])
Auto _id
MongoDB adds unique _id automatically
_id: ObjectId("...")
Return Value
Get inserted document IDs
insertedId: "..."
🔹 Insert One Document
Use insertOne() to add a single document to a collection:
// Insert one user
db.users.insertOne({
name: "John Smith",
email: "[email protected]",
age: 32,
city: "New York"
})
// MongoDB returns the inserted ID
// { acknowledged: true, insertedId: ObjectId("...") }
Output:
✓ Document inserted successfully
insertedId: ObjectId("507f1f77bcf86cd799439011")
🔹 Insert Multiple Documents
Use insertMany() to add multiple documents in a single operation:
// Insert multiple products
db.products.insertMany([
{
name: "Laptop",
price: 999,
category: "Electronics"
},
{
name: "Mouse",
price: 25,
category: "Accessories"
},
{
name: "Keyboard",
price: 75,
category: "Accessories"
}
])
// Returns array of inserted IDs
Output:
✓ 3 documents inserted
insertedIds: [ ObjectId("..."), ObjectId("..."), ObjectId("...") ]
🔹 Automatic _id Field
MongoDB automatically adds a unique _id field to each document if you don't provide one:
// Without _id (MongoDB creates it)
db.books.insertOne({
title: "MongoDB Guide",
author: "Jane Doe"
})
// With custom _id
db.books.insertOne({
_id: "book001",
title: "Advanced MongoDB",
author: "John Smith"
})
Output:
Document 1: _id: ObjectId("507f191e810c19729de860ea")
Document 2: _id: "book001"
🔹 Insert with Nested Documents
You can insert documents with nested objects and arrays:
// Insert document with nested data
db.customers.insertOne({
name: "Sarah Johnson",
email: "[email protected]",
address: {
street: "123 Main St",
city: "Boston",
state: "MA",
zip: "02101"
},
orders: [
{ item: "Laptop", price: 999 },
{ item: "Mouse", price: 25 }
],
registered: new Date()
})
Output:
✓ Document with nested data inserted
🔹 Insert Options
You can pass options to control insert behavior:
// Insert with ordered option (default: true)
db.items.insertMany(
[
{ name: "Item 1" },
{ name: "Item 2" },
{ name: "Item 3" }
],
{ ordered: false } // Continue on error
)
// Insert with write concern
db.logs.insertOne(
{ message: "System started" },
{ writeConcern: { w: "majority" } }
)
Options Explained:
- ordered: If false, continues inserting even if one fails
- writeConcern: Controls acknowledgment of write operations
🔹 Handling Insert Errors
MongoDB returns errors if insertion fails:
// Duplicate _id error
db.users.insertOne({ _id: 1, name: "Alice" })
db.users.insertOne({ _id: 1, name: "Bob" }) // Error!
// Catch errors in application code
try {
db.users.insertOne({ _id: 1, name: "Charlie" })
} catch (error) {
print("Insert failed: " + error)
}
Output:
✗ Error: E11000 duplicate key error
🔹 Complete Example
Here's a practical example of inserting various types of data:
// Switch to database
use schoolDB
// Insert single student
db.students.insertOne({
studentId: "S001",
name: "Emma Wilson",
age: 20,
major: "Computer Science",
gpa: 3.8
})
// Insert multiple courses
db.courses.insertMany([
{
courseId: "CS101",
title: "Intro to Programming",
credits: 3,
instructor: "Dr. Smith"
},
{
courseId: "CS201",
title: "Data Structures",
credits: 4,
instructor: "Dr. Johnson"
}
])
// Insert enrollment with references
db.enrollments.insertOne({
studentId: "S001",
courseId: "CS101",
semester: "Fall 2024",
grade: null // Not yet graded
})
// Verify insertions
db.students.countDocuments()
db.courses.countDocuments()
db.enrollments.countDocuments()
Output:
✓ Students: 1
✓ Courses: 2
✓ Enrollments: 1