MongoDB Best Practices for Production Applications
Running MongoDB in production requires careful attention to schema design, indexing, and operational concerns. Here are the essential practices every team should follow.
1. Schema Design: Embed vs. Reference
MongoDB gives you flexibility but also responsibility. The golden rule: embed data that is always accessed together, reference data that is accessed independently.
// ✅ Embed: order items always shown with order
{
_id: ObjectId(),
customer_id: ObjectId("..."),
created_at: ISODate(),
items: [
{ product_id: ObjectId(), name: "Widget", qty: 2, price: 29.99 }
],
total: 59.98
}
// ✅ Reference: products accessed separately
{
_id: ObjectId(),
name: "Widget",
price: 29.99,
inventory: 500
}
2. Always Use Compound Indexes for Sort + Filter
// Query: find active users, sort by last login
db.users.createIndex({ status: 1, last_login: -1 });
// Explain to verify index is used
db.users.find({ status: "active" })
.sort({ last_login: -1 })
.explain("executionStats");
💡 Rule of thumb: Follow the ESR rule — Equality fields first, Sort fields second, Range fields last.
3. Set Write Concern and Read Preference Intentionally
// High-durability writes (financial data)
db.transactions.insertOne(doc, { writeConcern: { w: "majority", j: true } });
// Allow reads from secondaries for analytics
db.reports.find(query).readPref("secondaryPreferred");
4. Enable WiredTiger Compression
WiredTiger (MongoDB default storage engine) supports snappy and zlib compression. Enable zlib for maximum space savings on large collections at the cost of slightly more CPU.
5. Monitor with Atlas or Ops Manager
Always enable slow query logging and set slowOpThresholdMs to 100ms. Review the Query Profiler weekly to catch regressions before users do.