Appearance
MongoDB Query Performance
Index Strategy for Queries
Rule: Every production query should use an index.
Check if index is used:
javascript
// mongosh: tạo dữ liệu mẫu rồi đọc explain
db.users.insertMany(Array.from({ length: 20000 }, (_, i) => ({ email: "u" + i + "@x.com", status: ["active", "inactive", "banned"][i % 3], age: 18 + (i % 60), createdAt: new Date(2025, 0, 1 + (i % 300)), country: i % 5 == 0 ? "US" : "VN" })))
db.users.createIndex({ email: 1 })
db.users.find({ email: "u5@x.com" }).explain("executionStats")Key metrics to check:
text
Kết quả (rút gọn, đo trên mongo:8.3 với 20 000 user):
executionStats.nReturned: 1
executionStats.totalKeysExamined: 1 (nên gần nReturned)
executionStats.totalDocsExamined: 1 (nên gần nReturned)
executionStats.executionTimeMillis: đổi theo máy (mục tiêu ví dụ < 100 ms cho OLTP)
executionStats.executionStages: FETCH → inputStage IXSCAN (indexName: email_1)
Không có index: executionStages là COLLSCAN, totalDocsExamined = 20000Performance goals:
- ✅
stage: "IXSCAN"(index scan, not collection scan) - ✅
totalDocsExamined≈nReturned(examine only what you return) - ✅
executionTimeMillis< 100ms for OLTP queries - ✅
totalKeysExamined/nReturnedclose to 1 (selectivity ratio; threshold depends on workload)
Compound Index Optimization
Left-to-right prefix rule:
javascript
// mongosh: tạo orders rồi thử từng truy vấn (đo trên 20 000 đơn)
db.orders.insertMany(Array.from({ length: 20000 }, (_, i) => ({ userId: i % 2000, status: i % 20 == 0 ? "pending" : "completed", createdAt: new Date(2025, 0, 1 + (i % 400)), amount: i % 100 })))
db.orders.createIndex({ status: 1, createdAt: -1, userId: 1 })
// ✅ Uses index (leftmost prefix)
db.orders.find({ status: "pending" })
db.orders.find({ status: "pending", createdAt: { $gte: ISODate("2025-01-01") }})
db.orders.find({ status: "pending", createdAt: { $gte: ISODate("2025-01-01") }, userId: 123 })
// ❌ Does NOT use index (skips leftmost): explain cho COLLSCAN
db.orders.find({ createdAt: { $gte: ISODate("2025-01-01") }})
db.orders.find({ userId: 123 })ESR Rule (Equality, Sort, Range)
javascript
// mongosh: chạy sau khối tạo users ở mục Index Strategy for Queries
// Query: WHERE status = 'active' ORDER BY createdAt LIMIT 10
db.users.createIndex({ status: 1, createdAt: -1 }) // E (equality), S (sort): explain không có stage SORT
// Query: WHERE status = 'active' AND age > 30 ORDER BY createdAt
db.users.createIndex({ status: 1, createdAt: -1, age: 1 }) // E, S, R (range)
// NOT: { status: 1, age: 1, createdAt: -1 } R trước S: explain có stage SORT (sắp xếp trong RAM)Why ESR order matters:
- Equality first: Narrows down quickly
- Sort second: Avoids in-memory sort (uses index order)
- Range last: Range conditions can't be used for further filtering
Covered Queries (No Document Fetch)
Best performance: Query satisfied entirely by index (never touch documents)
javascript
// mongosh: chạy sau khối tạo users ở mục Index Strategy for Queries
db.users.createIndex({ status: 1, email: 1, createdAt: 1 })
// Covered query (projection chỉ gồm trường có trong index)
db.users.find({ status: "active" }, { _id: 0, email: 1, createdAt: 1 })
// explain("executionStats"): PROJECTION_COVERED → IXSCAN, totalDocsExamined: 0 (không đụng document)
// Thêm _id vào projection: có FETCH, totalDocsExamined = số document khớp (đo trên mongo:8.3)Requirements for covered query:
- ✅ All query fields in index
- ✅ All projection fields in index
- ✅ Exclude
_idfrom projection (or include_idin index) - ❌ Can't cover: array fields (multikey on the projected field), geospatial; embedded-document fields CAN be covered (3.6+)
Aggregation Pipeline Optimization
Optimization principles:
- Push $match early (filter ASAP)
- Use indexes for $match and $sort
- $project early to reduce document size
- Avoid $lookup when possible (denormalize instead)
- Use $limit after $sort
Example:
javascript
// mongosh
db.users.insertMany(Array.from({ length: 5000 }, (_, i) => ({ _id: i, country: i % 5 == 0 ? "US" : "VN" })))
db.orders.insertMany(Array.from({ length: 5000 }, (_, i) => ({ userId: i % 100, amount: i })))
db.orders.createIndex({ userId: 1 })
// ✅ Viết $match trước $lookup (rõ ý, dùng index trên country nếu có)
db.users.aggregate([
{ $match: { country: "US" }},
{ $lookup: { from: "orders", localField: "_id", foreignField: "userId", as: "orders" }},
{ $unwind: "$orders" }
])
// Thứ tự $lookup → $match({ country }) → $unwind: trình tối ưu tự đẩy $match lên trước $lookup
// (explain: bộ lọc country nằm trong $cursor; $unwind gộp vào $lookup).
// $match lọc theo trường của kết quả lookup (vd "orders.amount") KHÔNG đẩy lên được: phải chờ lookup chạy xong.Use index for $match:
javascript
// mongosh: chạy sau khối tạo orders ở mục Compound Index Optimization
db.orders.createIndex({ status: 1, createdAt: 1 })
db.orders.aggregate([
{ $match: { status: "completed", createdAt: { $gte: ISODate("2025-01-01") }}}, // Uses index
{ $group: { _id: "$userId", total: { $sum: "$amount" }}},
{ $sort: { total: -1 }},
{ $limit: 10 }
])
// Kiểm tra: gọi db.orders.explain().aggregate([...cùng pipeline...]) và tìm IXSCAN trong winningPlan.
// Vị trí đổi theo bản: stages[0].$cursor.queryPlanner hoặc queryPlanner ở gốc (mongo:8.3 với $match + $group: queryPlanner.winningPlan.queryPlan)Avoid large $unwind:
javascript
// mongosh
db.products.insertOne({ name: "p", reviews: [{ rating: 5 }, { rating: 3 }, { rating: 5 }] })
// ❌ Bad: Unwind large array
db.products.aggregate([
{ $unwind: "$reviews" }, // 10,000 reviews → 10,000 docs
{ $match: { "reviews.rating": 5 }}
])
// ✅ Good: Use $filter
db.products.aggregate([
{ $project: {
name: 1,
fiveStarReviews: {
$filter: {
input: "$reviews",
as: "review",
cond: { $eq: ["$$review.rating", 5] }
}
}
}}
])Partial Index for Sparse Queries
Problem: Index on status where 95% of documents are "completed" (low selectivity)
Solution: Partial index for active statuses only
javascript
// mongosh: chạy sau khối tạo orders ở mục Compound Index Optimization
// Only index pending/processing orders (5% of total)
db.orders.createIndex(
{ status: 1, createdAt: -1 },
{
partialFilterExpression: {
status: { $in: ["pending", "processing"] }
}
}
)
// Query must match partial filter expression
db.orders.find({ status: "pending" }) // ✅ Uses partial index
db.orders.find({ status: "completed" }) // ❌ Không dùng được partial index. Nếu không còn index nào khác bắt đầu bằng status thì là COLLSCAN; chạy sau khối tạo orders ở mục Compound Index Optimization thì vẫn IXSCAN bằng index {status, createdAt, userId} có sẵn (đo trên mongo:8). Muốn thấy COLLSCAN: db.orders.dropIndexes() trước
// Chấp nhận được khi đơn completed hiếm khi bị truy vấnBenefits:
- ✅ Smaller index (95% less space)
- ✅ Faster writes (don't update index for completed orders)
- ✅ Faster reads (smaller index = more in RAM)
Text Index Optimization
Create text index:
javascript
// mongosh
db.articles.createIndex({ title: "text", body: "text", tags: "text" })Search:
javascript
// mongosh
// Simple search
db.articles.find({ $text: { $search: "mongodb tutorial" }})
// Phrase search
db.articles.find({ $text: { $search: "\"exact phrase\"" }})
// Exclude words
db.articles.find({ $text: { $search: "mongodb -mysql" }})
// Sort by text score (relevance)
db.articles.find(
{ $text: { $search: "mongodb" }},
{ score: { $meta: "textScore" }}
).sort({ score: { $meta: "textScore" }})Limitations:
- ❌ Only 1 text index per collection
- ⚠️ Compound text indexes allowed with ascending/descending keys, but not with multikey/geospatial keys
- ⚠️ Case-insensitive by default ($caseSensitive option available)
- ⚠️ Index chiếm dung lượng: đo bằng
db.collection.stats().indexSizes
Alternative: Use Atlas Search (Lucene-based, more powerful)
Geospatial Query Optimization
Create 2dsphere index:
javascript
// mongosh
db.places.createIndex({ location: "2dsphere" })Queries:
javascript
// mongosh: chạy sau khi nạp ít nhất một document có location (vd { name: "a", location: { type: "Point", coordinates: [-73.97, 40.78] } })
// Find places within radius
db.places.find({
location: {
$near: {
$geometry: {
type: "Point",
coordinates: [-73.9667, 40.78] // [longitude, latitude]
},
$maxDistance: 5000 // 5km in meters
}
}
})
// Find places within polygon
db.places.find({
location: {
$geoWithin: {
$geometry: {
type: "Polygon",
coordinates: [[[-74, 40.7], [-73.9, 40.7], [-73.9, 40.9], [-74, 40.9], [-74, 40.7]]]
}
}
}
})Query Performance Checklist
Before production:
- [ ] Every query uses an index (
explain()showsIXSCAN) - [ ]
totalDocsExamined≈nReturned(ngưỡng tuỳ workload, đo bằngexplain()) - [ ] Query time < 100ms (P95)
- [ ] Compound indexes follow ESR rule
- [ ] Use covered queries where possible
- [ ] $match early in aggregation pipeline
- [ ] Avoid $lookup (denormalize instead)
- [ ] Limit result size (
limit(), pagination)
Phải nhớ:
- Đọc
explain("executionStats"): tìmCOLLSCANvàSORTtrong cây stage, sototalDocsExaminedvớinReturned. - Xếp index theo ESR (Equality, Sort, Range); cột Range đứng sau cột Sort.
- Bật profiler khi cần:
slowmsmặc định 100 ms, mức mặc định 0 (tắt); kiểm bằngdb.getProfilingStatus().