Skip to content

MongoDB Deep Dive ​

Theo bảng xếp hạng document store của DB-Engines, MongoDB thường đứng đầu (thứ hạng đổi theo tháng: xem trang xếp hạng).

Tổng quan kiến trúc ​

text
MONGODB ARCHITECTURE

Application Layer
├── Drivers (Node.js, Python, Java, etc.)
└── Connection Pooling

Query Router (mongos)
├── Query routing to shards
└── Aggregation merging

Config Servers (Replica Set)
├── Metadata storage
├── Shard key ranges
└── Chunk distribution

Shards (Replica Sets)
├── Primary (read/write)
├── Secondary (read replicas)
└── Arbiter (voting only)

Storage Engine (WiredTiger)
├── Document-level locking
├── Compression (snappy default; zlib/zstd)
└── Checkpointing

Khái niệm cốt lõi ​

Documents (BSON)

javascript
// minh hoạ, không chạy độc lập (document BSON)
{
  _id: ObjectId("507f1f77bcf86cd799439011"),  // Auto-generated unique ID
  email: "john@example.com",
  profile: {                                   // Embedded document
    name: "John Doe",
    age: 30,
    address: {
      city: "San Francisco",
      zip: "94102"
    }
  },
  orders: [                                    // Embedded array
    { id: 1, total: 99.99, date: ISODate("2025-01-01") },
    { id: 2, total: 149.99, date: ISODate("2025-01-05") }
  ],
  tags: ["premium", "verified"],               // Simple array
  createdAt: ISODate("2024-12-01T10:00:00Z")
}

Collections

  • Không ép schema (các document trong cùng collection có thể khác trường)
  • Tự tạo khi insert lần đầu
  • Không có foreign key (join ở tầng ứng dụng)

Databases

  • Không gian tên chứa các collection
  • Isolated (own users, permissions)

Các loại index ​

1. Single Field Index (SQL: B-Tree Index)

javascript
// mongosh
db.users.createIndex({ email: 1 })  // 1 = ascending, -1 = descending
// Use: WHERE email = 'john@example.com'

2. Compound Index (SQL: Composite Index - leftmost prefix rule giống nhau)

javascript
// mongosh
db.users.createIndex({ status: 1, createdAt: -1 })
// Use: WHERE status = 'active' ORDER BY createdAt DESC
// Left-to-right prefix rule: Can use {status: 1} alone

3. Multikey Index (Arrays) (SQL: GIN Index cho JSONB/Array)

javascript
// mongosh
db.products.createIndex({ tags: 1 })
// Indexes each element in array
// Query: db.products.find({ tags: "electronics" })

4. Text Index (Full-Text Search) (SQL: GIN + tsvector / FULLTEXT)

javascript
// mongosh
db.articles.createIndex({ title: "text", body: "text" })
// Query: db.articles.find({ $text: { $search: "mongodb tutorial" }})

5. Geospatial Index (SQL: GiST / SPATIAL Index)

javascript
// mongosh
db.places.createIndex({ location: "2dsphere" })
// Query: db.places.find({ location: { $near: { $geometry: { type: "Point", coordinates: [-73.9, 40.7] }}}})

6. Wildcard Index (Flexible Schema) (SQL: gần nhất là GIN trên JSONB trong PostgreSQL; chưa so sánh chi tiết)

javascript
// mongosh
db.products.createIndex({ "attributes.$**": 1 })
// Indexes all fields under 'attributes' (arbitrary keys)

7. Partial Index (Filtered) (SQL: Partial Index - query phải match filter)

javascript
// mongosh
db.orders.createIndex(
  { status: 1, createdAt: 1 },
  { partialFilterExpression: { status: { $in: ["pending", "processing"] }}}
)
// Only indexes documents where status is pending/processing
// Saves space (don't index 'completed' orders)

8. Sparse Index (SQL: Partial Index với WHERE col IS NOT NULL)

javascript
// mongosh
db.users.createIndex({ phone: 1 }, { sparse: true })
// Only indexes documents WHERE phone field EXISTS

9. Unique Index (SQL: UNIQUE constraint / UNIQUE index)

javascript
// mongosh
// Nếu đã chạy khối Single Field ở trên trên cùng database: db.users.dropIndex("email_1") trước, nếu không báo IndexKeySpecsConflict (đã đo mongo:8)
db.users.createIndex({ email: 1 }, { unique: true })
// Enforces uniqueness (like SQL UNIQUE constraint)

10. TTL Index (Auto-Expiration) (SQL: thường dùng cron job/scheduled task để xoá dòng hết hạn)

javascript
// mongosh
db.sessions.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 })
// Xoá document khi createdAt cũ hơn 1 giờ; tiến trình nền chạy mỗi 60 giây và không bảo đảm xoá ngay lúc hết hạn (đã đo: expireAfterSeconds 1 vẫn còn doc sau vài giây, hết trong 65 giây)

⚠️ GOTCHA: Index Build Lớn Làm Tăng Replication Lag Và Co Oplog Window

Index build trên collection lớn tốn I/O của mọi member nên làm tăng replication lag và có thể làm oplog window co lại. Cách dựng khác nhau theo bản:

  • Trước 4.2: createIndex() kiểu foreground giữ khoá độc quyền, chặn ghi
  • 4.2 trở lên: build chỉ giữ khoá độc quyền ở đầu và cuối; tuỳ chọn background bị bỏ qua
  • 4.4 trở lên: index build chạy đồng thời trên mọi member dữ liệu; primary chỉ commit khi đủ commit quorum (mặc định votingMembers)

Vì sao vẫn nguy hiểm:

  • Build đọc cả collection trên từng member, tranh I/O với tải thật
  • Secondary chậm thì lag tăng; oplog window ngắn hơn thời gian build thì secondary phải resync đầy đủ

Kịch bản minh hoạ, không phải sự cố có nguồn (số không đo):

javascript
// mongosh
// Collection: 500M documents, 200GB
db.events.createIndex({ userId: 1, timestamp: -1 })
// Build kéo dài hàng giờ; nếu oplog window ngắn hơn thời gian build thì secondary cần resync đầy đủ

Cách phát hiện:

javascript
// mongosh
// Check for in-progress index builds
db.currentOp({
  $or: [
    { op: "command", "command.createIndexes": { $exists: true }},
    { msg: /^Index Build/ }
  ]
})

// Monitor replication lag during index builds
rs.printSecondaryReplicationInfo()

Phòng tránh:

  1. Dựng index lúc tải thấp, theo dõi rs.printSecondaryReplicationInfo() trong lúc build
  2. Với bản dưới 4.4 hoặc cần giữ secondary khỏi tải build: dựng index theo kiểu rolling (từng secondary, rồi step down primary):
    bash
    # Step 1: Stop secondary, build index offline, restart
    # Step 2: Repeat for all secondaries
    # Step 3: Step down primary, build index on former primary
  3. Theo dõi oplog window: timeDiffHours phải lớn hơn thời gian build:
    javascript
    // mongosh
    db.getReplicationInfo()
  4. Chỉnh commit quorum cho build đang chạy (4.4 trở lên; indexNames bắt buộc, không có build đang chạy thì lỗi IndexNotFound):
    javascript
    // mongosh
    db.runCommand({
      setIndexCommitQuorum: "events",
      indexNames: ["userId_1_timestamp_-1"],
      commitQuorum: "votingMembers"
    })

Bài học: trên 4.4 trở lên build không còn chặn secondary theo thứ tự, nhưng vẫn phải đo lag và oplog window.

→ See also: MongoDB Production Checklist, MongoDB Anti-Patterns

Hiệu năng truy vấn ​

Explain Plan

javascript
// mongosh
db.users.find({ status: "active" }).explain("executionStats")

Kết quả minh hoạ (rút gọn, chỉ các trường chính):

text
{
  executionStats: {
    executionTimeMillis: 5,          // Total time
    totalKeysExamined: 100,          // Index keys scanned
    totalDocsExamined: 100,          // Documents scanned
    nReturned: 100,                  // Documents returned
    executionStages: {
      stage: "IXSCAN",               // Index scan (good)
      // stage: "COLLSCAN"           // Collection scan (bad)
      indexName: "status_1"
    }
  }
}

Performance goals:

  • totalDocsExamined ≈ nReturned (chỉ quét đúng số document trả về)
  • stage: "IXSCAN", không phải "COLLSCAN"
  • executionTimeMillis thấp hơn SLO của bạn (ví dụ minh hoạ: dưới 100ms cho OLTP)

Covered Query (Best Performance)

javascript
// mongosh
db.users.drop()
db.users.insertMany([
  { email: "a@x.com", name: "A", status: "active" },
  { email: "b@x.com", name: "B", status: "inactive" },
  { email: "c@x.com", name: "C", status: "active" },
  { email: "d@x.com", name: "D", status: "inactive" }
])
db.users.createIndex({ status: 1, email: 1 })
const c = db.users.find(
  { status: "active" },
  { _id: 0, email: 1 }  // Project only indexed fields
).explain("executionStats").executionStats
printjson({ nReturned: c.nReturned, totalKeysExamined: c.totalKeysExamined, totalDocsExamined: c.totalDocsExamined })
// Kết quả đo (mongo:8): { nReturned: 2, totalKeysExamined: 2, totalDocsExamined: 0 }  ← không chạm document

⚠️ GOTCHA: Partial Index Bị Bỏ Qua Khi Query Thiếu Điều Kiện Lọc (COLLSCAN Bất Ngờ)

Query không chứa điều kiện của partialFilterExpression thì MongoDB không dùng partial index và quét cả collection. Kết quả vẫn đủ document; rủi ro thật là COLLSCAN bất ngờ.

Vì sao:

  • Partial index chỉ chứa document khớp partialFilterExpression
  • Planner chỉ cân nhắc nó khi predicate của query là tập con của filter đó; dùng index sẽ làm thiếu kết quả thì bị loại
  • find({}) không có predicate nên rơi về COLLSCAN và trả đủ mọi document

Ví dụ đã đo (mongo:8):

javascript
// mongosh
db.users.drop()
db.users.insertMany([
  { email: "a@x.com", name: "A", status: "active" },
  { email: "b@x.com", name: "B", status: "inactive" },
  { email: "c@x.com", name: "C", status: "active" },
  { email: "d@x.com", name: "D", status: "inactive" }
])
db.users.createIndex(
  { email: 1, name: 1 },
  { partialFilterExpression: { status: "active" }}
)
const s = db.users.find({}, { _id: 0, email: 1, name: 1 }).explain("executionStats").executionStats
printjson({ nReturned: s.nReturned, totalDocsExamined: s.totalDocsExamined })
// Kết quả đo: { nReturned: 4, totalDocsExamined: 4 }  ← COLLSCAN, đủ 4 document

Cách phát hiện: chạy explain("executionStats") cho query lẽ ra dùng index; thấy COLLSCAN là query thiếu điều kiện của partial filter.

Phòng tránh:

  1. Thêm điều kiện của partial filter (status: "active") vào query; đây là điều kiện cần để planner được cân nhắc partial index, không bảo đảm nó được chọn, nên đo bằng explain
  2. Giữ thêm một index thường cho query không kèm điều kiện
  3. Đừng dùng partial index cho query quan trọng mà không kiểm explain

Bài học: partial index không làm mất kết quả; nó làm mất index khi query không nói rõ điều kiện.

→ See also: MongoDB Anti-Patterns, MongoDB Query Performance

Pipeline aggregation ​

Tạo dữ liệu cho pipeline bên dưới:

javascript
// mongosh
db.users.drop()
db.orders.drop()
db.users.insertMany([{ _id: 1, country: "VN" }, { _id: 2, country: "US" }])
db.orders.insertMany([
  { userId: 1, status: "completed", total: 10, createdAt: ISODate("2025-02-01") },
  { userId: 1, status: "completed", total: 20, createdAt: ISODate("2025-03-01") }
])
javascript
// mongosh (chạy sau khối tạo dữ liệu ở trên)
db.orders.aggregate([
  // Stage 1: Filter
  { $match: { status: "completed", createdAt: { $gte: ISODate("2025-01-01") }}},

  // Stage 2: Lookup (left join)
  { $lookup: {
      from: "users",
      localField: "userId",
      foreignField: "_id",
      as: "user"
  }},

  // Stage 3: Unwind array
  { $unwind: "$user" },

  // Stage 4: Group and aggregate
  { $group: {
      _id: "$user.country",
      totalRevenue: { $sum: "$total" },
      orderCount: { $sum: 1 },
      avgOrderValue: { $avg: "$total" }
  }},

  // Stage 5: Sort
  { $sort: { totalRevenue: -1 }},

  // Stage 6: Limit
  { $limit: 10 }
])

Tối ưu pipeline:

  • Đặt $match càng sớm càng tốt (lọc trước)
  • Dùng index cho $match và $sort
  • $project sớm để giảm kích thước document
  • Tránh $lookup khi có thể (denormalize thay thế)

⚠️ GOTCHA: $lookup trên collection shard (cái giá của scatter-gather)

Từ MongoDB 5.1, from của $lookup có thể là collection shard. Doc $lookup không mô tả $lookup được định tuyến thế nào (mongos hay shard, một shard hay mọi shard) và không nêu mức suy giảm hiệu năng; đừng giả định scatter-gather, hãy đo bằng explain trên cluster của bạn.

Why it happens:

  • Doc $lookup không nêu cách định tuyến truy vấn sang collection ngoài khi nó là shard; các bước 'mongos broadcast', 'mỗi shard tự tra', 'gộp ở mongos' là suy đoán chưa kiểm (chưa chạy: cần cluster N nút)
  • doc không nêu vai trò của khoá shard khi $lookup; kiểm bằng explain

Real-world impact:

javascript
// Sharded setup: orders (sharded by userId), products (sharded by category)
db.orders.aggregate([
  { $match: { userId: "user123" }},  // Hits 1 shard ✓
  { $lookup: {                        // Queries ALL shards ✗
      from: "products",
      localField: "productId",
      foreignField: "_id",
      as: "product"
  }}
])
// Kịch bản minh hoạ, số không đo: so sánh bằng explain trên cluster của bạn

How to detect:

javascript
// mongosh (minh hoạ, không chạy độc lập: thay [...] bằng pipeline thật)
// Check explain plan for sharded $lookup
db.orders.aggregate([...]).explain()
// Đọc phần `shards` và `mergeType` của explain để xem shard nào tham gia; tên trường và giá trị khác nhau theo bản, chưa kiểm trên cluster (chưa chạy: cần cluster N nút)
// Chỉ coi là chi phí đáng lo khi explain cho thấy số shard tham gia lớn hơn dự kiến

Prevention:

  1. Denormalize dữ liệu (nhúng thông tin sản phẩm vào document đơn hàng)
  2. Shard collection được join theo khoá join (shard products theo _id nếu join bằng productId)
  3. Dùng $graphLookup khi thật cần (doc không nêu số so sánh; đo bằng explain)
  4. Tổng hợp trước dữ liệu (lưu kết quả join thành collection riêng)

→ See also: MongoDB Anti-Patterns, MongoDB Scaling Strategies

Replica set ​

text
PRIMARY ──────┬──────> SECONDARY (read replica)
  │           │
  │           └──────> SECONDARY (read replica)
  │
  └──────────────────> ARBITER (voting only, no data)

Write Concerns

javascript
// mongosh
// w=1: Acknowledge from primary only (fast; NOT the default since 5.0)
db.users.insertOne({ name: "An" }, { writeConcern: { w: 1 }})

// w="majority": Acknowledge from majority (safe)
db.users.insertOne({ name: "Binh" }, { writeConcern: { w: "majority" }})

// w=3: Acknowledge from 3 nodes (slower, safer); cần replica set có ít nhất 3 member mang dữ liệu
db.users.insertOne({ name: "Chi" }, { writeConcern: { w: 3 }})

⚠️ GOTCHA: Bầu cử replica set khi đang ghi (mất ghi với w=1)

Ghi với w: 1 được primary xác nhận trước khi nhân bản. Primary sập trước khi secondary nhận được thì ghi đó bị rollback khi bầu primary mới, dù client đã nhận ack.

Vì sao xảy ra:

  • w: 1 nghĩa là chỉ primary xác nhận, chưa chờ secondary
  • Primary mới không có ghi này trong oplog
  • Khi primary cũ vào lại cụm, ghi đó bị rollback và lưu vào file rollback BSON (createRollbackDataFiles mặc định true); nó biến mất khỏi dữ liệu sống cho tới khi bạn áp lại tay

Cách phát hiện:

javascript
// mongosh
// Độ trễ từng secondary so với primary
rs.printSecondaryReplicationInfo()

// Oplog window (timeDiffHours) và dung lượng oplog
db.getReplicationInfo()

Phòng tránh:

  • Dùng w: "majority" cho ghi quan trọng (tiền, dữ liệu người dùng); đây là mặc định từ 5.0 trừ khi cụm có arbiter hoặc bạn ghi đè
  • Thêm retry ở ứng dụng kèm khoá idempotency
  • Theo dõi oplog window (timeDiffHours) và lag của secondary

Bài học: ack của w: 1 chỉ chứng minh primary đã nhận, không chứng minh ghi sống sót qua failover.

→ See also: MongoDB Transactions, MongoDB Anti-Patterns

Read Preferences

javascript
// mongosh
// primary: Read from primary only (default, consistent)
db.users.find().readPref("primary")

// primaryPreferred: Primary if available, else secondary
db.users.find().readPref("primaryPreferred")

// secondary: Read from secondary (eventual consistency)
db.users.find().readPref("secondary")

// nearest: Lowest latency (geo-distributed)
db.users.find().readPref("nearest")

⚠️ GOTCHA: Oplog quá nhỏ (replication tụt lại, phải resync toàn bộ)

If your oplog is too small and a secondary falls behind (network issue, maintenance, high write load), the secondary cannot catch up and requires a FULL RESYNC from scratch (thời gian tuỳ kích thước dữ liệu và mạng, đo bằng thử trên bản sao; doc nêu initial sync làm giảm hiệu năng của primary nguồn).

Vì sao xảy ra:

  • Oplog là capped collection (kích thước cố định, bộ đệm vòng)
  • Khi secondary offline/chậm, primary vẫn ghi và các entry oplog cũ bị ghi đè
  • Khi secondary kết nối lại, entry oplog nó cần đã mất
  • MongoDB buộc initial sync toàn bộ (sao chép cả dataset từ primary)

Kịch bản thực tế:

  • Oplog size: 5GB (mặc định là 5% dung lượng đĩa trống, tối thiểu 990MB, tối đa 50GB)
  • Tốc độ ghi: 500 MB/giờ
  • Oplog window: 10 giờ
  • Secondary offline 12 giờ → phải resync toàn bộ!

How to detect:

javascript
// Check current oplog window (how far behind secondary can be)
db.getReplicationInfo()
// Kết quả minh hoạ: configuredLogSizeMB: 5120, timeDiffHours: 9.5  ← TOO SMALL!

// Check if secondary is falling behind
rs.printSecondaryReplicationInfo()
// If replication lag approaching oplog window → DANGER!

Prevention:

  • Chọn oplog window dài hơn thời gian bảo trì hoặc đứt mạng lâu nhất bạn chấp nhận, kèm biên an toàn (24-48 giờ chỉ là ví dụ minh hoạ, không phải khuyến nghị của doc)
  • Resize oplog: db.adminCommand({replSetResizeOplog: 1, size: 102400}) (100GB)
  • Theo dõi timeDiffHours của db.getReplicationInfo() trong production
  • Đặt cảnh báo khi lag tiến gần oplog window (ngưỡng 50% là ví dụ minh hoạ, đo theo tải của bạn)

→ See also: MongoDB Scaling Strategies, MongoDB Monitoring

Phân mảnh dữ liệu (sharding) ​

Shard Key Selection (CRITICAL)

javascript
// mongosh, kết nối mongos (chưa chạy: cần sharded cluster nhiều nút)
// Good: High cardinality + even distribution
sh.shardCollection("app.users", { userId: "hashed" })  // Hash-based

// Cân nhắc: range query theo thời gian; đặt userId trước timestamp vì timestamp đứng đầu là khoá tăng đơn điệu (hot shard)
sh.shardCollection("app.events", { userId: 1, timestamp: 1 })

// Bad: Low cardinality (hot shard)
sh.shardCollection("app.users", { country: 1 })  // Few values

// Bad: Monotonically increasing (last shard gets all writes)
sh.shardCollection("app.events", { _id: 1 })  // ObjectId is increasing

Shard key characteristics:

  • High cardinality: Many distinct values
  • Phân bố đều: không có hot shard
  • Cô lập truy vấn: truy vấn chỉ chạm một shard (không scatter-gather)

Zone sharding (data locality)

javascript
// mongosh, kết nối mongos (minh hoạ, không chạy độc lập; chưa chạy: cần cluster N nút; collection phải đã shard theo { country: 1 } thì mới gán zone theo khoá này, và khoá thấp cardinality chỉ là ví dụ zone)
sh.addShardToZone("shard0000", "US")
sh.addShardToZone("shard0001", "EU")
sh.updateZoneKeyRange("app.users", { country: "US" }, { country: "US\xff" }, "US")
sh.updateZoneKeyRange("app.users", { country: "GB" }, { country: "GB\xff" }, "EU")

Tính năng đáng chú ý của MongoDB (time-series 5.0+, Queryable Encryption, change streams 3.6+) ​

Time-Series Collections

javascript
// mongosh
db.createCollection("sensors", {
  timeseries: {
    timeField: "timestamp",
    metaField: "sensorId",
    granularity: "seconds"
  }
})
// Optimized storage for time-series (IoT, metrics)

Queryable Encryption Queryable Encryption: trường mã hoá vẫn truy vấn được (equality; range theo doc), khác CSFLE; kiểm bảng tương thích theo phiên bản.

Change Streams

javascript
// Node.js (driver mongodb, replica set hoặc sharded cluster)
const changeStream = db.collection("users").watch()
changeStream.on("change", (change) => {
  console.log(change)  // { operationType: "insert", fullDocument: {...}}
})
// Real-time data sync, event-driven architectures

⚠️ GOTCHA: ghi w: 1 bị rollback khi failover, change stream không thấy nhưng client vẫn tin đã ghi

Change stream chỉ phát event đã majority-committed. Ghi w: 1 bị rollback khi failover thì không có trong stream và cũng không có trong database. Rủi ro thật nằm ở client: nó đã nhận ack nên tin ghi thành công.

Vì sao xảy ra:

  • Change stream đọc từ oplog và chỉ trả các thay đổi đã majority-committed
  • Ghi w: 1 chưa nhân bản khi primary sập bị rollback, nên không bao giờ thành event
  • Ứng dụng nhận ack, gửi phản hồi cho khách, nhưng consumer của stream không thấy gì và document cũng biến mất khỏi dữ liệu sống

Ví dụ minh hoạ (không chạy độc lập, cần failover thật):

javascript
// Node.js (minh hoạ, không chạy độc lập)
await db.collection("orders").insertOne({ orderId: "12345", status: "pending" }, { writeConcern: { w: 1 } })  // client nhận ack

// Primary sập trước khi nhân bản, secondary lên làm primary, ghi bị rollback

// Consumer không bao giờ nhận event; đơn 12345 không còn trong database
// (nằm trong file rollback BSON trên primary cũ)

Cách phát hiện:

javascript
// Node.js (minh hoạ, không chạy độc lập)
// Event 'invalidate' đến khi collection bị drop/rename (không phải khi failover); mở lại stream bằng startAfter
changeStream.on("change", (change) => {
  if (change.operationType === "invalidate") {
    console.error("Stream đã đóng: mở lại bằng startAfter với resume token cuối")
  }
})
  • Đối chiếu số đơn phía ứng dụng với số document sau mỗi lần failover; tìm file rollback bằng thư mục rollback trong dbPath

Phòng tránh:

  1. Ghi quan trọng dùng w: "majority":
    javascript
    // Node.js
    await db.collection("orders").insertOne(
      { orderId: "12345", status: "pending" },
      { writeConcern: { w: "majority" }}
    )
  2. Thêm polling bù và khoá idempotency:
    javascript
    // Node.js
    setInterval(async () => {
      const missedOrders = await db.collection("orders").find({
        status: "pending",
        notificationSent: { $ne: true }
      }).toArray()
      // Process missed orders
    }, 300000)
  3. Lưu resume token và mở lại stream từ đó:
    javascript
    // Node.js
    const changeStream = db.collection("orders").watch([], { resumeAfter: lastResumeToken })
  4. Theo dõi độ trễ giữa lúc ghi và lúc stream nhận event.

Bài học: ack w: 1 không bảo đảm event; chỉ ghi majority-committed mới xuất hiện trong change stream.

→ See also: MongoDB Transactions, MongoDB Production Checklist


Máy tính ước lượng cỡ cluster MongoDB ​

Purpose: Calculate MongoDB cluster sizing (nodes, RAM, CPU, storage) and cost estimates based on your workload requirements. Mọi hằng số trong hàm là giả định minh hoạ; thay bằng số đo và giá thật của bạn.

How to use:

  1. Define your requirements (QPS, data size, availability)
  2. Chạy hàm tính toán
  3. Xem khuyến nghị sizing và bảng phân rã chi phí
  4. Chỉnh tham số nếu có cảnh báo
javascript
// Node.js: giá trị trong hàm là giả định minh hoạ, thay bằng số đo/giá thật của bạn
function calculateMongoDBCluster(requirements) {
  const {
    qpsRead = 1000,        // Read queries per second
    qpsWrite = 100,        // Write queries per second
    dataSize = 100,        // Total data size in GB
    availability = 'high', // 'basic' | 'high' | 'enterprise'
  } = requirements

  // Working set giả định 30% dữ liệu (đo working set thật rồi thay)
  const workingSet = dataSize * 0.3
  const ramPerNode = Math.max(workingSet, 8) // Minimum 8GB RAM

  // CPU: giả định 5K QPS mỗi 4 vCPU (benchmark query mix thật rồi thay)
  const totalQPS = qpsRead + qpsWrite
  const cpuPerNode = Math.ceil(totalQPS / 5000) * 4

  const nodeCount = availability === 'basic' ? 1
                  : availability === 'high' ? 3
                  : 5 // enterprise

  // Storage = (data x 1.2 index + oplog) x 1.5 growth
  const oplogSize = Math.max(dataSize * 0.05, 50) // 5% or 50GB min
  const storagePerNode = (dataSize * 1.2 + oplogSize) * 1.5

  // Giá minh hoạ cho họ r6g (giá tăng gấp đôi theo cỡ); kiểm giá thật theo region/ngày
  const tiers = [
    { name: 'r6g.xlarge', ramGB: 32, hourly: 0.201 },
    { name: 'r6g.2xlarge', ramGB: 64, hourly: 0.403 },
    { name: 'r6g.4xlarge', ramGB: 128, hourly: 0.806 },
    { name: 'r6g.8xlarge', ramGB: 256, hourly: 1.613 },
    { name: 'r6g.12xlarge', ramGB: 384, hourly: 2.419 },
    { name: 'r6g.16xlarge', ramGB: 512, hourly: 3.226 },
  ]
  const tier = tiers.find(t => t.ramGB >= ramPerNode) ?? tiers[tiers.length - 1]
  const needsSharding = ramPerNode > 512
  const monthlyCost = nodeCount * tier.hourly * 730
  const storageCost = nodeCount * storagePerNode * 0.08 // gp3 minh hoạ

  return {
    cluster: {
      nodes: nodeCount,
      instanceType: tier.name,
      ramPerNode: `${Math.ceil(ramPerNode)}GB`,
      cpuPerNode,
      storagePerNode: `${Math.ceil(storagePerNode)}GB`,
    },
    cost: {
      compute: `$${monthlyCost.toFixed(2)}/month`,
      storage: `$${storageCost.toFixed(2)}/month`,
      total: `$${(monthlyCost + storageCost).toFixed(2)}/month`,
      perNode: `$${(monthlyCost / nodeCount).toFixed(2)}/month`,
    },
    recommendations: [
      needsSharding ? 'Working set vượt 512GB RAM: cần shard' : null,
      ramPerNode < 16 ? 'Working set nhỏ: cỡ r6g.xlarge đã đủ RAM; đo cache hit ratio trước khi tăng cỡ' : null,
      totalQPS / (nodeCount * 5000) > 0.7 ? 'Trên 70% công suất giả định: thêm node đọc hoặc shard' : null,
      oplogSize < 100 ? 'Oplog tính theo giả định calculator (5% dữ liệu, tối thiểu 50GB): đo oplog window thật bằng rs.printReplicationInfo()' : null,
    ].filter(Boolean)
  }
}

// Example usage: E-commerce product catalog
const sizing = calculateMongoDBCluster({
  qpsRead: 10000,
  qpsWrite: 1000,
  dataSize: 500,
  availability: 'high',
})

console.log(JSON.stringify(sizing, null, 2))

Kết quả khi chạy (Node 22):

json
{
  "cluster": {
    "nodes": 3,
    "instanceType": "r6g.8xlarge",
    "ramPerNode": "150GB",
    "cpuPerNode": 12,
    "storagePerNode": "975GB"
  },
  "cost": {
    "compute": "$3532.47/month",
    "storage": "$234.00/month",
    "total": "$3766.47/month",
    "perNode": "$1177.49/month"
  },
  "recommendations": [
    "Trên 70% công suất giả định: thêm node đọc hoặc shard",
    "Tăng oplog lên 100GB+ cho production"
  ]
}

Real-world sizing examples:

Example 1: Small SaaS application

javascript
// Node.js (chạy sau khi khai báo calculateMongoDBCluster ở trên)
calculateMongoDBCluster({
  qpsRead: 500,
  qpsWrite: 50,
  dataSize: 20,
  availability: 'basic',  // Single node for dev/staging
})
// Kết quả khi chạy: 1x r6g.xlarge, compute $146.73/month, tổng $155.61/month

Example 2: Medium e-commerce site

javascript
// Node.js (chạy sau khi khai báo calculateMongoDBCluster ở trên)
calculateMongoDBCluster({
  qpsRead: 5000,
  qpsWrite: 500,
  dataSize: 200,
  availability: 'high',  // 3-node replica set
})
// Kết quả khi chạy: 3x r6g.2xlarge (60GB RAM mỗi node), compute $882.57/month, tổng $986.97/month

Example 3: High-traffic social app

javascript
// Node.js (chạy sau khi khai báo calculateMongoDBCluster ở trên)
calculateMongoDBCluster({
  qpsRead: 50000,
  qpsWrite: 5000,
  dataSize: 2000,
  availability: 'enterprise',  // 5-node for global HA
})
// Kết quả khi chạy: 5x r6g.16xlarge, compute $11774.90/month, tổng $13274.90/month
// RAM mỗi node 600GB vượt 512GB: recommendations báo cần shard

Key sizing rules:

  1. RAM ≥ working set đã đo (index + document nóng): hãy đo, đừng giả định một % của dữ liệu
  2. CPU: benchmark đúng hỗn hợp truy vấn của bạn; không có con số QPS-trên-vCPU chung (điều chỉnh cho aggregation phức tạp)
  3. Storage = (data × 1.2 (indexes) + oplog) × 1.5 (growth)
  4. Oplog = 5% of data, tối thiểu 50GB (giả định của calculator; đo oplog window thật)
  5. Replica set: tối thiểu 3 thành viên; doc khuyến nghị 3 nút mang dữ liệu (1 primary + 2 secondaries; arbiter thay nút thứ ba chỉ khi chi phí không cho phép)

Khi nào cần shard (vượt giới hạn một replica set):

  • Dữ liệu/working set hoặc write throughput vượt mức một replica set phục vụ được (hãy đo)
  • Working set > RAM của instance type lớn nhất (r6g.16xlarge = 512GB)

→ See also: MongoDB Scaling Strategies, MongoDB Production Setup


Phải nhớ

  • w: "majority" cho ghi quan trọng; ack của w: 1 không sống sót qua failover.
  • Đọc explain("executionStats") trước khi tin một index: COLLSCAN hoặc totalDocsExamined lớn hơn nReturned là tín hiệu xấu.
  • Khoá shard không để trường tăng đơn điệu đứng đầu.

Tự kiểm Bạn tạo partial index { email: 1, name: 1 } với partialFilterExpression: { status: "active" }, rồi find({}, { _id: 0, email: 1, name: 1 }) trả đủ mọi user nhưng chậm. Vì sao, và cách kiểm?

Đáp án

Query không có điều kiện status: "active" nên planner không dùng partial index và chạy COLLSCAN (kết quả vẫn đủ). Kiểm bằng explain("executionStats"): thấy COLLSCAN, totalDocsExamined bằng số document.