Practical Code Examples
Setting Up MongoDB Environment
Install MongoDB on Ubuntu 22.04
sudo apt-get update
sudo apt-get install -y mongodb
sudo systemctl start mongodb
mongo
Example 1: User Profile Insertion
Python with PyMongo
from pymongo import MongoClient
## Connect to MongoDB
client = MongoClient('mongodb://localhost:27017/')
db = client['labex_database']
users_collection = db['users']
## Create user document
user_profile = {
"username": "labexuser",
"email": "[email protected]",
"age": 28,
"skills": ["Python", "MongoDB", "Docker"],
"active": True
}
## Insert single document
result = users_collection.insert_one(user_profile)
print(f"Inserted document ID: {result.inserted_id}")
Example 2: Product Catalog Insertion
Node.js with MongoDB Driver
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017';
const dbName = 'labex_store';
MongoClient.connect(url, (err, client) => {
const db = client.db(dbName);
const products = db.collection('products');
const newProduct = {
name: "MongoDB Tutorial Book",
price: 29.99,
category: "Education",
tags: ["database", "tutorial", "learning"]
};
products.insertOne(newProduct, (err, result) => {
console.log(`Product inserted with ID: ${result.insertedId}`);
});
});
Example 3: Complex Document Insertion
MongoDB Shell Example
use labex_analytics
db.events.insertOne({
event_type: "user_registration",
timestamp: new Date(),
user_data: {
id: ObjectId(),
source: "web_platform",
registration_details: {
method: "email",
referral: "newsletter"
}
},
metadata: {
ip_address: "192.168.1.100",
device: "desktop"
}
})
Insertion Workflow
graph TD
A[Prepare Document] --> B[Validate Data]
B --> C[Choose Insertion Method]
C --> D[Execute insertOne()]
D --> E[Handle Result]
E --> F[Error Handling]
Common Insertion Scenarios
Scenario |
Recommended Method |
Considerations |
Single Document |
insertOne() |
Simple, straightforward |
Bulk Documents |
insertMany() |
More efficient |
Upsert Operations |
replaceOne() with upsert |
Update or insert |
Conditional Insertion |
insertOne() with validation |
Ensure data integrity |
Error Handling Strategies
- Use try-catch blocks
- Implement retry mechanisms
- Log detailed error information
- Validate documents before insertion
- Minimize document size
- Use appropriate indexes
- Choose correct write concern
- Batch insert when possible
By exploring these practical examples, developers can gain hands-on experience with MongoDB document insertion techniques across different programming environments.