Insert Documents
Master inserting documents into MongoDB collections using insertOne() and insertMany(). Understand BSON data types, auto-generated ObjectIds, ordered vs unordered inserts, and write concerns for production use.
Documents are the core unit of data in MongoDB — they're JSON-like objects stored in BSON (Binary JSON) format. This episode covers every way to insert data into MongoDB, from single documents to bulk inserts.
insertOne() — Insert a Single Document
use blogApp
// Insert a single document
db.posts.insertOne({
title: "Getting Started with MongoDB",
content: "MongoDB is a document-oriented database...",
author: "John Doe",
tags: ["mongodb", "nosql", "database"],
likes: 0,
published: true,
createdAt: new Date()
})
Output:
{
acknowledged: true,
insertedId: ObjectId('65a1b2c3d4e5f6a7b8c9d0e1')
}
The insertedId is the auto-generated _id field — MongoDB's unique identifier for every document.
ObjectId Explained
Every document in MongoDB has a unique _id field. If you don't provide one, MongoDB generates an ObjectId automatically:
// ObjectId structure: 65a1b2c3d4e5f6a7b8c9d0e1
// |--------|-----|-----|------|
// timestamp random counter
// (4 bytes) (5 bytes)(3 bytes)
- Timestamp — First 4 bytes encode the creation time (unix timestamp)
- Random value — 5 random bytes for uniqueness per machine/process
- Counter — 3-byte incrementing counter for documents created in the same second
// You can extract the timestamp from an ObjectId
ObjectId('65a1b2c3d4e5f6a7b8c9d0e1').getTimestamp()
// Output: ISODate('2024-01-12T10:30:27.000Z')
// You can also provide your own _id
db.posts.insertOne({
_id: "custom-id-123",
title: "Custom ID Post"
})
// Or use a numeric _id
db.posts.insertOne({
_id: 1001,
title: "Numeric ID Post"
})
insertMany() — Insert Multiple Documents
db.users.insertMany([
{
name: "Alice",
email: "alice@example.com",
age: 28,
role: "developer"
},
{
name: "Bob",
email: "bob@example.com",
age: 34,
role: "designer"
},
{
name: "Charlie",
email: "charlie@example.com",
age: 25,
role: "developer"
},
{
name: "Diana",
email: "diana@example.com",
age: 31,
role: "manager"
}
])
Output:
{
acknowledged: true,
insertedIds: {
'0': ObjectId('...'),
'1': ObjectId('...'),
'2': ObjectId('...'),
'3': ObjectId('...')
}
}
Ordered vs Unordered Inserts
By default, insertMany() performs ordered inserts — if one document fails, all subsequent documents are skipped:
// Ordered (default) — stops at first error
db.users.insertMany([
{ _id: 1, name: "One" },
{ _id: 1, name: "Duplicate!" }, // Error: duplicate _id
{ _id: 2, name: "Two" } // This is SKIPPED
])
// Unordered — continues past errors
db.users.insertMany([
{ _id: 3, name: "Three" },
{ _id: 3, name: "Duplicate!" }, // Error, but continues
{ _id: 4, name: "Four" } // This IS inserted
], { ordered: false })
Use ordered: false for bulk imports where you want to insert as many documents as possible, even if some fail.
BSON Data Types
MongoDB stores data in BSON format, which supports more types than JSON:
db.examples.insertOne({
// String
name: "MongoDB",
// Number types
intValue: 42, // Double (default)
intExplicit: NumberInt(42), // 32-bit integer
longValue: NumberLong("9223372036854775807"), // 64-bit integer
decimalValue: NumberDecimal("19.99"), // 128-bit decimal
// Boolean
isActive: true,
// Date
createdAt: new Date(), // Current date/time
specificDate: ISODate("2024-01-15T10:30:00Z"),
// Null
deletedAt: null,
// Array
tags: ["web", "database", "nosql"],
// Nested object (embedded document)
address: {
street: "123 Main St",
city: "Mumbai",
zip: "400001"
},
// ObjectId
relatedId: ObjectId(),
// Regular expression
pattern: /^mongo/i,
// Binary data
// Used for files, images, etc.
// Timestamp (internal MongoDB use)
ts: Timestamp()
})
Nested Documents and Arrays
One of MongoDB's strengths is storing complex, nested data in a single document:
db.orders.insertOne({
orderNumber: "ORD-2024-001",
customer: {
name: "John Doe",
email: "john@example.com",
address: {
street: "456 Oak Ave",
city: "Bangalore",
state: "Karnataka",
pin: "560001"
}
},
items: [
{ product: "Laptop", price: 75000, qty: 1 },
{ product: "Mouse", price: 500, qty: 2 },
{ product: "Keyboard", price: 2000, qty: 1 }
],
total: 78000,
status: "processing",
createdAt: new Date()
})
This is a key difference from SQL — in a relational database, this would require at least 3 tables (orders, customers, order_items). In MongoDB, it's a single document.
Write Concerns
Write concerns control the acknowledgment level for write operations:
// Default — acknowledged write
db.posts.insertOne(
{ title: "Safe Write" },
{ writeConcern: { w: 1 } }
)
// Write to majority of replica set members
db.posts.insertOne(
{ title: "Majority Write" },
{ writeConcern: { w: "majority", wtimeout: 5000 } }
)
// Unacknowledged write (fire and forget — fastest but risky)
db.posts.insertOne(
{ title: "Fast Write" },
{ writeConcern: { w: 0 } }
)
What's Next
You can now insert any type of data into MongoDB. In the next episode, we'll learn how to query and retrieve documents using find(), findOne(), comparison operators, and more.