Introduction
MongoDB powers production applications across virtually every industry. Its flexible schema, horizontal scalability, and rich feature set make it ideal for diverse use cases. This article explores real-world MongoDB implementations, providing patterns and best practices you can apply to your own projects.
We will examine production scenarios ranging from web applications to mobile apps, IoT platforms to content management systems. Each use case includes implementation details, architecture patterns, and lessons learned from production deployments.
Web Applications
Web applications represent the most common MongoDB use case. The document model maps naturally to JSON, making MongoDB an excellent fit for web backends.
E-Commerce Platform
// E-commerce data model
// Products collection
{
_id: ObjectId("..."),
sku: "LAPTOP-PRO-15",
name: "Professional Laptop 15\"",
description: "High-performance laptop for professionals",
category: "Electronics",
tags: ["laptop", "portable", "work"],
price: 1299.99,
stock: 50,
attributes: {
cpu: "Intel i7",
ram: "16GB",
storage: "512GB SSD",
display: "15.6\" FHD"
},
images: [
"/images/products/laptop-1.jpg",
"/images/products/laptop-2.jpg"
],
reviews: [
{ user_id: "user1", rating: 5, comment: "Great laptop!" },
{ user_id: "user2", rating: 4, comment: "Good performance" }
],
created_at: ISODate("2026-01-15"),
updated_at: ISODate("2026-03-01")
}
// Orders collection
{
_id: ObjectId("..."),
order_number: "ORD-2026-001234",
user_id: ObjectId("..."),
items: [
{
product_id: ObjectId("..."),
sku: "LAPTOP-PRO-15",
quantity: 1,
price: 1299.99
},
{
product_id: ObjectId("..."),
sku: "MOUSE-WIRELESS",
quantity: 2,
price: 29.99
}
],
subtotal: 1359.97,
tax: 108.80,
shipping: 0,
total: 1468.77,
status: "shipped",
shipping_address: {
street: "123 Main St",
city: "New York",
state: "NY",
zip: "10001"
},
timeline: [
{ status: "placed", timestamp: ISODate("2026-02-15T10:30:00Z") },
{ status: "paid", timestamp: ISODate("2026-02-15T10:31:00Z") },
{ status: "shipped", timestamp: ISODate("2026-02-16T14:00:00Z") }
]
}
Shopping Cart Implementation
// Shopping cart operations
// Add to cart
async function addToCart(userId, productId, quantity) {
const db = client.db('ecommerce');
const cart = db.collection('carts');
await cart.updateOne(
{ user_id: userId },
{
$inc: {
`items.${productId}`: quantity
},
$set: { updated_at: new Date() }
},
{ upsert: true }
);
}
// Get cart with product details
async function getCart(userId) {
const db = client.db('ecommerce');
const cart = db.collection('carts');
const products = db.collection('products');
const cartDoc = await cart.findOne({ user_id: userId });
if (!cartDoc || !cartDoc.items) {
return { items: [], total: 0 };
}
// Get product IDs from cart
const productIds = Object.keys(cartDoc.items);
// Fetch product details
const productDocs = await products.find(
{ _id: { $in: productIds.map(id => new ObjectId(id)) } }
).toArray();
// Merge cart items with product details
const items = productDocs.map(product => ({
product,
quantity: cartDoc.items[product._id.toString()],
subtotal: product.price * cartDoc.items[product._id.toString()]
}));
const total = items.reduce((sum, item) => sum + item.subtotal, 0);
return { items, total };
}
// Checkout
async function checkout(userId, shippingAddress) {
const session = client.startSession();
try {
await session.withTransaction(async () => {
const { items, total } = await getCart(userId);
// Validate stock
for (const item of items) {
const product = await db.products.findOneAndUpdate(
{ _id: item.product._id, stock: { $gte: item.quantity } },
{ $inc: { stock: -item.quantity } },
{ session }
);
if (!product) {
throw new Error(`Insufficient stock for ${item.product.name}`);
}
}
// Create order
await db.orders.insertOne({
user_id: userId,
items: items.map(i => ({
product_id: i.product._id,
sku: i.product.sku,
quantity: i.quantity,
price: i.product.price
})),
total,
shipping_address: shippingAddress,
status: 'placed',
timeline: [{ status: 'placed', timestamp: new Date() }]
}, { session });
// Clear cart
await db.carts.deleteOne({ user_id: userId }, { session });
});
return { success: true };
} finally {
await session.endSession();
}
}
User Management
// User authentication and profiles
// Create user with secure password
async function createUser(email, password, profile) {
const db = client.db('app');
// Hash password (use bcrypt in production)
const hashedPassword = await bcrypt.hash(password, 12);
const user = {
email,
password_hash: hashedPassword,
profile: {
first_name: profile.firstName,
last_name: profile.lastName,
avatar: profile.avatar,
bio: profile.bio
},
settings: {
email_notifications: true,
marketing_emails: false,
theme: 'light',
language: 'en'
},
roles: ['user'],
verified: false,
created_at: new Date(),
last_login: null
};
await db.users.insertOne(user);
return user;
}
// Verify credentials
async function verifyCredentials(email, password) {
const user = await db.users.findOne({ email });
if (!user) {
return null;
}
const valid = await bcrypt.compare(password, user.password_hash);
if (!valid) {
return null;
}
// Update last login
await db.users.updateOne(
{ _id: user._id },
{ $set: { last_login: new Date() } }
);
return user;
}
Mobile Applications
MongoDB excels for mobile applications, especially with MongoDB Realm for offline-first capabilities.
Offline-First Architecture
// Realm schema for offline-first mobile app
const UserSchema = {
name: 'User',
primaryKey: '_id',
properties: {
_id: 'objectId',
username: 'string',
email: 'string',
profile: 'Profile?'
}
};
const NoteSchema = {
name: 'Note',
primaryKey: '_id',
properties: {
_id: 'objectId',
title: 'string',
content: 'string',
tags: 'string[]',
created_at: 'date',
updated_at: 'date',
sync_status: { type: 'string', default: 'pending' }
}
};
// Sync configuration
const syncConfig = {
user: app.currentUser,
partitionValue: 'myapp',
callback: {
onError: (error) => {
console.error('Sync error:', error);
},
onSuccess: () => {
console.log('Sync complete');
}
}
};
// Create Realm with sync
const realm = await Realm.open({
schema: [UserSchema, NoteSchema],
sync: syncConfig
});
// Work offline
const note = realm.create('Note', {
_id: new ObjectId(),
title: 'My Note',
content: 'Note content',
created_at: new Date(),
updated_at: new Date(),
sync_status: 'pending'
});
// Changes sync automatically when online
realm.write(() => {
note.content = 'Updated content';
note.sync_status = 'pending';
});
Push Notifications
// Store device tokens
{
_id: ObjectId("..."),
user_id: ObjectId("..."),
device_token: "fcm_token_here",
platform: "ios", // or "android"
app_version: "1.2.3",
last_active: ISODate("2026-03-11"),
notifications_enabled: true
}
// Notification preferences
{
_id: ObjectId("..."),
user_id: ObjectId("..."),
preferences: {
new_message: { push: true, email: false },
new_follower: { push: true, email: true },
promotion: { push: false, email: true },
digest: { push: false, email: true }
}
}
IoT and Time Series
MongoDB’s flexible schema and time series collections make it excellent for IoT applications.
IoT Data Model
// Device registry
{
_id: ObjectId("..."),
device_id: "sensor-001",
type: "temperature_sensor",
location: {
building: "Warehouse A",
floor: 2,
coordinates: { lat: 40.7128, lng: -74.0060 }
},
firmware: "v2.1.0",
status: "online",
last_seen: ISODate("2026-03-11T10:30:00Z"),
metadata: {
manufacturer: "SensorCo",
model: "TempPro-2000",
serial_number: "SN123456"
}
}
// Telemetry data (time series collection)
{
_id: ObjectId("..."),
device_id: "sensor-001",
timestamp: ISODate("2026-03-11T10:30:00Z"),
readings: {
temperature: 22.5,
humidity: 45.2,
pressure: 1013.25
},
battery: 87,
signal_strength: -65
}
// Alerts
{
_id: ObjectId("..."),
device_id: "sensor-001",
type: "threshold_exceeded",
severity: "warning",
message: "Temperature exceeded threshold",
value: 28.5,
threshold: 25,
acknowledged: false,
created_at: ISODate("2026-03-11T10:35:00Z"),
acknowledged_at: null,
acknowledged_by: null
}
Time Series Queries
// Create time series collection
db.createCollection('telemetry', {
timeseries: {
timeField: 'timestamp',
metaField: 'device_id',
granularity: 'minutes'
}
});
// Query temperature over time
db.telemetry.aggregate([
{
$match: {
device_id: 'sensor-001',
timestamp: {
$gte: new Date('2026-03-01'),
$lt: new Date('2026-03-11')
}
}
},
{
$group: {
_id: {
$dateToString: { format: '%Y-%m-%d', date: '$timestamp' }
},
avgTemp: { $avg: '$readings.temperature' },
maxTemp: { $max: '$readings.temperature' },
minTemp: { $min: '$readings.temperature' },
readings: { $sum: 1 }
}
},
{ $sort: { _id: 1 } }
]);
// Detect anomalies
db.telemetry.aggregate([
{
$match: {
device_id: 'sensor-001',
timestamp: { $gte: new Date('2026-03-10') }
}
},
{
$setWindowFields: {
sortBy: { timestamp: 1 },
output: {
avgTemp: {
$avg: '$readings.temperature',
window: { documents: ['unbounded', 'current'] }
},
stdDev: {
$stdDevPop: '$readings.temperature',
window: { documents: ['unbounded', 'current'] }
}
}
}
},
{
$match: {
$expr: {
$gt: [
{ $abs: { $subtract: ['$readings.temperature', '$avgTemp'] } },
{ $multiply: ['$stdDev', 3] }
]
}
}
}
]);
Content Management
MongoDB’s flexible schema is ideal for content management systems.
CMS Data Model
// Articles collection
{
_id: ObjectId("..."),
slug: "mongodb-best-practices-2026",
title: "MongoDB Best Practices in 2026",
excerpt: "Learn the latest MongoDB best practices...",
content: "<h1>MongoDB Best Practices</h1><p>...</p>",
author: {
id: ObjectId("..."),
name: "John Smith",
avatar: "/authors/john.jpg"
},
status: "published",
published_at: ISODate("2026-03-01"),
updated_at: ISODate("2026-03-10"),
tags: ["MongoDB", "Database", "Best Practices"],
category: "Technology",
featured: true,
views: 12500,
seo: {
meta_title: "MongoDB Best Practices | Expert Guide",
meta_description: "Discover the latest MongoDB best practices...",
keywords: ["mongodb", "database", "best practices"]
},
translations: {
es: ObjectId("..."),
fr: ObjectId("..."),
de: ObjectId("...")
},
related_articles: [
ObjectId("..."),
ObjectId("...")
]
}
// Media library
{
_id: ObjectId("..."),
filename: "mongodb-architecture.jpg",
original_filename: "architecture-diagram.png",
mime_type: "image/jpeg",
size: 245678,
dimensions: { width: 1920, height: 1080 },
url: "/media/2026/03/mongodb-architecture.jpg",
thumbnail_url: "/media/2026/03/mongodb-architecture-thumb.jpg",
alt_text: "MongoDB Architecture Diagram",
uploaded_by: ObjectId("..."),
uploaded_at: ISODate("2026-03-05"),
tags: ["mongodb", "architecture", "diagram"],
usage: [
{ content_id: ObjectId("..."), field: 'featured_image' }
]
}
Version Control
// Article version history
{
_id: ObjectId("..."),
article_id: ObjectId("..."),
version: 3,
content: "<h1>MongoDB Best Practices</h1>...",
changed_by: ObjectId("..."),
changed_at: ISODate("2026-03-10T14:30:00Z"),
change_summary: "Updated performance section",
diff: {
added: ["Performance section updated with new benchmarks"],
removed: [],
modified: ["Performance section"]
}
}
Real-Time Analytics
MongoDB supports real-time analytics with aggregation pipelines.
Analytics Schema
// User events (clickstream)
{
_id: ObjectId("..."),
session_id: "sess_abc123",
user_id: ObjectId("..."),
event_type: "page_view",
event_data: {
page: "/products/laptop",
referrer: "/search?q=laptop"
},
timestamp: ISODate("2026-03-11T10:30:00Z"),
device: {
type: "desktop",
browser: "Chrome",
os: "Windows",
screen_width: 1920
},
location: {
country: "US",
region: "NY",
city: "New York"
}
}
// Daily metrics (computed)
{
_id: ObjectId("..."),
date: ISODate("2026-03-10"),
metrics: {
unique_visitors: 15420,
page_views: 89500,
avg_session_duration: 245, // seconds
bounce_rate: 0.35,
top_pages: [
{ page: "/", views: 25000 },
{ page: "/products", views: 18500 }
],
top_referrers: [
{ source: "google", visits: 8000 },
{ source: "twitter", visits: 3500 }
]
}
}
Real-Time Dashboard
// Live metrics computation
async function computeLiveMetrics() {
const db = client.db('analytics');
const pipeline = [
{
$match: {
timestamp: { $gte: new Date(Date.now() - 3600000) } // Last hour
}
},
{
$group: {
_id: {
minute: { $minute: '$timestamp' },
event_type: '$event_type'
},
count: { $sum: 1 },
unique_users: { $addToSet: '$user_id' }
}
},
{
$project: {
_id: 1,
count: 1,
unique_users: { $size: '$unique_users' }
}
}
];
return await db.user_events.aggregate(pipeline);
}
Gaming Applications
MongoDB handles gaming workloads with high write throughput and flexible schemas.
Player Profile
// Player document
{
_id: ObjectId("..."),
player_id: "player_123456",
username: "ProGamer99",
email: "[email protected]",
profile: {
level: 45,
experience: 1250000,
rank: "Diamond",
avatar_url: "/avatars/player123.jpg"
},
stats: {
games_played: 1542,
wins: 892,
losses: 650,
win_rate: 0.578,
kills: 15420,
deaths: 8920,
kdr: 1.73,
avg_score: 2450
},
inventory: {
coins: 15000,
gems: 500,
items: [
{ item_id: "weapon_001", quantity: 1, equipped: true },
{ item_id: "skin_003", quantity: 1, equipped: false }
]
},
achievements: [
{ id: "first_win", unlocked_at: ISODate("2025-06-15") },
{ id: "win_streak_10", unlocked_at: ISODate("2025-08-20") }
],
friends: [
ObjectId("..."),
ObjectId("...")
],
settings: {
audio_volume: 0.8,
music_volume: 0.6,
graphics_quality: "high",
notifications: true
},
last_login: ISODate("2026-03-11T10:30:00Z"),
created_at: ISODate("2025-01-01")
}
// Match history
{
_id: ObjectId("..."),
match_id: "match_abc123",
game_mode: "ranked",
player_id: "player_123456",
team: "blue",
result: "win",
stats: {
kills: 12,
deaths: 5,
assists: 8,
score: 3200,
duration: 1845 // seconds
},
timestamp: ISODate("2026-03-11T10:30:00Z"),
map: "dust_ii",
region: "na"
}
Best Practices Summary
Schema Design
- Embed documents for one-to-few relationships
- Reference for one-to-many and many-to-many
- Avoid deep nesting (keep under 3 levels)
- Use appropriate field types (dates, numbers, booleans)
Performance
- Create indexes for query fields
- Use projection to limit returned fields
- Implement pagination for large results
- Monitor slow queries with explain()
Security
- Enable authentication
- Use role-based access control
- Encrypt data at rest and in transit
- Implement field-level security for sensitive data
Operations
- Use replica sets for high availability
- Implement regular backups
- Monitor with appropriate tools
- Plan for scaling with sharding
External Resources
Conclusion
MongoDB’s flexibility and scalability make it suitable for virtually any application type. From e-commerce platforms to mobile apps, IoT systems to gaming applications, MongoDB powers production workloads across industries.
Key patterns covered:
- Web applications with flexible schemas
- Mobile apps with offline-first capabilities
- IoT with time series data
- Content management with versioning
- Real-time analytics
- Gaming with high write throughput
These real-world patterns provide a foundation for building robust, scalable applications with MongoDB. Adapt these patterns to your specific requirements and leverage MongoDB’s features to build exceptional applications.
This completes our comprehensive MongoDB article series, covering fundamentals, operations, internals, trends, AI integration, and production use cases.
Comments