Advanced Insertion Strategies
Bulk Write Operations
Bulk write operations allow multiple write actions in a single request:
graph TD
A[Bulk Write] --> B[Insert]
A --> C[Update]
A --> D[Delete]
A --> E[Replace]
Example Bulk Write
db.users.bulkWrite([
{
insertOne: {
document: {
"username": "labex_user1",
"email": "[email protected]"
}
}
},
{
updateOne: {
filter: { "username": "existing_user" },
update: { $set: { "status": "active" } }
}
}
])
Write Concern Strategies
Write Concern |
Description |
Performance |
w: 0 |
No acknowledgment |
Fastest |
w: 1 |
Acknowledge primary |
Balanced |
w: majority |
Majority of replicas |
Most reliable |
Configuring Write Concern
db.users.insertOne(
{ "username": "labex_user" },
{
writeConcern: {
w: "majority",
wtimeout: 5000
}
}
)
Atomic Document Updates
Atomic Operators
graph TD
A[Atomic Operators] --> B[$set]
A --> C[$inc]
A --> D[$push]
A --> E[$pull]
Example Atomic Update
db.users.updateOne(
{ "username": "labex_user" },
{
$set: { "email": "[email protected]" },
$inc: { "login_count": 1 }
}
)
Upsert Operations
Upsert combines insert and update:
db.users.updateOne(
{ "username": "labex_user" },
{
$set: {
"email": "[email protected]",
"last_login": new Date()
}
},
{ upsert: true }
)
Document Validation
Schema Validation Rules
db.createCollection("users", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["username", "email"],
properties: {
username: {
bsonType: "string",
description: "must be a string and is required"
},
email: {
bsonType: "string",
pattern: "^.+@labex\\.io$",
description: "must be a valid LabEx email"
}
}
}
}
})
- Use batch insertions
- Minimize document size
- Create appropriate indexes
- Use write concern wisely
Error Handling Strategies
try {
const result = db.users.insertMany(documents, { ordered: false });
print("Inserted " + result.insertedCount + " documents");
} catch (error) {
print("Bulk insert encountered errors: " + error.message);
print("Partially inserted documents: " + error.result.nInserted);
}
Advanced Insertion Patterns
Time-Series Data Insertion
db.performance_logs.insertOne({
"timestamp": new Date(),
"server": "labex-server-01",
"cpu_usage": 65.5,
"memory_usage": 4096
})
Best Practices
- Use bulk operations for efficiency
- Implement proper error handling
- Validate documents before insertion
- Choose appropriate write concerns
- Monitor and optimize insertion performance
By mastering these advanced insertion strategies, you'll become proficient in managing complex data scenarios in MongoDB during your LabEx learning journey.