MongoDB Drivers
Python (PyMongo)
Connection and Setup
from pymongo import MongoClient
from pymongo.errors import ConnectionFailure, BulkWriteError
from bson import ObjectId
from datetime import datetime
# Basic connection
client = MongoClient('mongodb://localhost:27017/')
db = client.myapp
collection = db.users
# Connection with authentication
client = MongoClient(
'mongodb://username:password@localhost:27017/',
authSource='admin'
)
# Connection pool configuration
client = MongoClient(
'mongodb://localhost:27017/',
maxPoolSize=50,
minPoolSize=10,
maxIdleTimeMS=30000,
serverSelectionTimeoutMS=5000
)
# Connection string with options
uri = "mongodb://localhost:27017/mydb?retryWrites=true&w=majority"
client = MongoClient(uri)
CRUD Operations
# Insert operations
document = {
"name": "John Doe",
"email": "john@example.com",
"created_at": datetime.utcnow()
}
# Insert one
result = collection.insert_one(document)
print(f"Inserted ID: {result.inserted_id}")
# Insert many
documents = [
{"name": "Alice", "email": "alice@example.com"},
{"name": "Bob", "email": "bob@example.com"}
]
result = collection.insert_many(documents)
print(f"Inserted IDs: {result.inserted_ids}")
# Find operations
user = collection.find_one({"email": "john@example.com"})
users = list(collection.find({"age": {"$gte": 18}}))
# Find with projection
user = collection.find_one(
{"email": "john@example.com"},
{"name": 1, "email": 1, "_id": 0}
)
# Update operations
result = collection.update_one(
{"email": "john@example.com"},
{"$set": {"last_login": datetime.utcnow()}}
)
print(f"Modified count: {result.modified_count}")
# Update many
result = collection.update_many(
{"status": "inactive"},
{"$set": {"archived": True}}
)
# Upsert
result = collection.update_one(
{"email": "new@example.com"},
{"$set": {"name": "New User", "created_at": datetime.utcnow()}},
upsert=True
)
# Delete operations
result = collection.delete_one({"email": "john@example.com"})
result = collection.delete_many({"status": "deleted"})
Aggregation
# Basic aggregation
pipeline = [
{"$match": {"status": "active"}},
{"$group": {
"_id": "$department",
"count": {"$sum": 1},
"avg_salary": {"$avg": "$salary"}
}},
{"$sort": {"count": -1}}
]
results = list(collection.aggregate(pipeline))
# Aggregation with options
results = list(collection.aggregate(
pipeline,
allowDiskUse=True,
maxTimeMS=30000
))
Error Handling
try:
result = collection.insert_one(document)
except ConnectionFailure:
print("Failed to connect to MongoDB")
except BulkWriteError as bwe:
print(f"Bulk write error: {bwe.details}")
except Exception as e:
print(f"Unexpected error: {e}")
Node.js (MongoDB Driver)
Connection and Setup
const { MongoClient, ObjectId } = require('mongodb');
// Basic connection
const uri = 'mongodb://localhost:27017';
const client = new MongoClient(uri);
async function connectToMongoDB() {
try {
await client.connect();
console.log('Connected to MongoDB');
const db = client.db('myapp');
const collection = db.collection('users');
return { db, collection };
} catch (error) {
console.error('Connection failed:', error);
throw error;
}
}
// Connection with options
const client = new MongoClient(uri, {
maxPoolSize: 50,
minPoolSize: 10,
maxIdleTimeMS: 30000,
serverSelectionTimeoutMS: 5000,
retryWrites: true
});
CRUD Operations
async function crudOperations() {
const { db, collection } = await connectToMongoDB();
try {
// Insert operations
const document = {
name: 'John Doe',
email: 'john@example.com',
createdAt: new Date()
};
const insertResult = await collection.insertOne(document);
console.log('Inserted ID:', insertResult.insertedId);
// Insert many
const documents = [
{ name: 'Alice', email: 'alice@example.com' },
{ name: 'Bob', email: 'bob@example.com' }
];
const insertManyResult = await collection.insertMany(documents);
// Find operations
const user = await collection.findOne({ email: 'john@example.com' });
const users = await collection.find({ age: { $gte: 18 } }).toArray();
// Find with options
const activeUsers = await collection.find(
{ status: 'active' },
{ projection: { name: 1, email: 1, _id: 0 } }
).limit(10).sort({ createdAt: -1 }).toArray();
// Update operations
const updateResult = await collection.updateOne(
{ email: 'john@example.com' },
{ $set: { lastLogin: new Date() } }
);
// Update many
await collection.updateMany(
{ status: 'inactive' },
{ $set: { archived: true } }
);
// Upsert
await collection.updateOne(
{ email: 'new@example.com' },
{ $set: { name: 'New User', createdAt: new Date() } },
{ upsert: true }
);
// Delete operations
await collection.deleteOne({ email: 'john@example.com' });
await collection.deleteMany({ status: 'deleted' });
} finally {
await client.close();
}
}
Aggregation
async function aggregationExample() {
const { collection } = await connectToMongoDB();
const pipeline = [
{ $match: { status: 'active' } },
{
$group: {
_id: '$department',
count: { $sum: 1 },
avgSalary: { $avg: '$salary' }
}
},
{ $sort: { count: -1 } }
];
const results = await collection.aggregate(pipeline).toArray();
console.log('Aggregation results:', results);
}
Transactions
async function transactionExample() {
const session = client.startSession();
try {
await session.withTransaction(async () => {
const usersCollection = db.collection('users');
const ordersCollection = db.collection('orders');
// Update user
await usersCollection.updateOne(
{ _id: ObjectId('...') },
{ $inc: { orderCount: 1 } },
{ session }
);
// Insert order
await ordersCollection.insertOne({
userId: ObjectId('...'),
items: [...],
total: 99.99,
createdAt: new Date()
}, { session });
});
console.log('Transaction completed successfully');
} catch (error) {
console.error('Transaction failed:', error);
} finally {
await session.endSession();
}
}
Change Streams
async function watchChanges() {
const { collection } = await connectToMongoDB();
const changeStream = collection.watch([
{ $match: { operationType: { $in: ['insert', 'update'] } } }
]);
changeStream.on('change', (change) => {
console.log('Change detected:', change);
switch (change.operationType) {
case 'insert':
console.log('New document:', change.fullDocument);
break;
case 'update':
console.log('Updated fields:', change.updateDescription);
break;
}
});
changeStream.on('error', (error) => {
console.error('Change stream error:', error);
});
}
Connection Management
class MongoDBManager {
constructor(uri, options = {}) {
this.client = new MongoClient(uri, {
maxPoolSize: 50,
minPoolSize: 5,
...options
});
this.db = null;
}
async connect(dbName) {
try {
await this.client.connect();
this.db = this.client.db(dbName);
console.log('Connected to MongoDB');
} catch (error) {
console.error('Connection failed:', error);
throw error;
}
}
async disconnect() {
try {
await this.client.close();
console.log('Disconnected from MongoDB');
} catch (error) {
console.error('Disconnect failed:', error);
}
}
getCollection(name) {
if (!this.db) {
throw new Error('Database not connected');
}
return this.db.collection(name);
}
async healthCheck() {
try {
const result = await this.db.admin().ping();
return result.ok === 1;
} catch (error) {
return false;
}
}
}
// Usage
const mongoManager = new MongoDBManager('mongodb://localhost:27017');
async function main() {
await mongoManager.connect('myapp');
const users = mongoManager.getCollection('users');
const result = await users.find({}).limit(5).toArray();
console.log('Users:', result);
await mongoManager.disconnect();
}
Connection String Examples
Local Development
// Basic local connection
"mongodb://localhost:27017/myapp"
// With authentication
"mongodb://username:password@localhost:27017/myapp"
// With options
"mongodb://localhost:27017/myapp?retryWrites=true&w=majority"
Production/Replica Set
// Replica set
"mongodb://user:pass@host1:27017,host2:27017,host3:27017/myapp?replicaSet=rs0"
// MongoDB Atlas
"mongodb+srv://username:password@cluster.mongodb.net/myapp?retryWrites=true&w=majority"
// With SSL and authentication
"mongodb://user:pass@host:27017/myapp?ssl=true&authSource=admin"
Best Practices
Connection Pooling
# Python - Configure connection pool
client = MongoClient(
'mongodb://localhost:27017/',
maxPoolSize=100,
minPoolSize=10,
maxIdleTimeMS=30000,
waitQueueTimeoutMS=5000
)
// Node.js - Connection pool settings
const client = new MongoClient(uri, {
maxPoolSize: 100,
minPoolSize: 10,
maxIdleTimeMS: 30000,
serverSelectionTimeoutMS: 5000,
socketTimeoutMS: 20000
});
Error Handling Patterns
# Python error handling
from pymongo.errors import (
ConnectionFailure,
ServerSelectionTimeoutError,
WriteError,
BulkWriteError
)
try:
collection.insert_one(document)
except ConnectionFailure:
# Handle connection issues
pass
except ServerSelectionTimeoutError:
# Handle timeout
pass
except WriteError as e:
# Handle write errors
print(f"Write error: {e.details}")
// Node.js error handling
try {
await collection.insertOne(document);
} catch (error) {
if (error.name === 'MongoNetworkError') {
// Handle network issues
} else if (error.name === 'MongoWriteError') {
// Handle write errors
} else {
// Handle other errors
console.error('Unexpected error:', error);
}
}