পাঠ ০৯ · ২৯-এর মধ্যে · মডিউল ২
Home / AI Courses / Data Engineering / MongoDB ও NoSQL

MongoDB ও NoSQL

MongoDB & the NoSQL family — when documents beat tables
৭ মিনিট পড়া মাঝারি · Intermediate MongoDB shell

এই পাঠে যা শিখবেন

  • NoSQL-এর চারটি family — কী, কখন কোনটি
  • MongoDB document model — collection, document, BSON
  • CRUD ও aggregation pipeline — হাতে-কলমে query
  • NoSQL কখন জেতে, কখন আত্মঘাতী — Bangladesh real-world উদাহরণে

১ · NoSQL — "Not Only SQL", কেন এসেছিল

NoSQLNoSQL"Not Only SQL" — relational table-row model বাদে অন্য data model ব্যবহার করে এমন DB। শব্দটি ১৯৯৮-এ Carlo Strozzi ব্যবহার করেছিলেন; ২০০৯-এ এটি rebranded — Google BigTable, Amazon Dynamo, MongoDB-র যুগে। ২০০৭-০৯ সালের সৃষ্টি। কারণ — Google, Amazon, Facebook এত বিশাল scale-এ এসেছিল যে traditional relational DB একক server-এ আর fit করত না। তারা নিজেরাই বানালেন — Google: BigTable; Amazon: Dynamo; Facebook: Cassandra।

NoSQL-এর চারটি family

১) Document: MongoDB, CouchDB — JSON-সদৃশ document।
২) Key-value: Redis, DynamoDB, etcd — সবচেয়ে সরল mapping।
৩) Wide-column: Cassandra, HBase, ScyllaDB — column-family, time-series।
৪) Graph: Neo4j, Amazon Neptune, ArangoDB — node ও edge।

বাংলাদেশে — Pathao-র real-time location tracking Redis (key-value)। Daraz-এর product catalog Elasticsearch (search engine, NoSQL-সদৃশ)। Shohoz-এর session store Redis। Foodpanda-র historical event log Cassandra-class system। MongoDB অনেক startup-এ initial choice — schema দ্রুত বদলায় বলে।

২ · CAP theorem — NoSQL-এর দার্শনিক ভিত্তি

CAP theoremCAP TheoremEric Brewer-এর ২০০০ সালের conjecture, ২০০২-এ Gilbert ও Lynch প্রমাণ করেন। distributed system-এ Consistency, Availability, Partition tolerance — তিনটির মাত্র দু'টি একসাথে পাওয়া যায়। বলে — distributed system-এ network partition হলে আপনাকে Consistency ও Availability-র মধ্যে একটি বাছতে হবে।

  • CP system: consistent কিন্তু partition-এ unavailable। MongoDB (default), HBase।
  • AP system: available কিন্তু eventually consistent। Cassandra, DynamoDB।
  • CA: single-node DB; partition হলে আর system নেই। Postgres single instance।
বাস্তবতা: CAP একটি sharp triangle না — modern DB tunable consistency দেয়। MongoDB-র read concern, Cassandra-র consistency level — query-by-query trade-off। PACELC theorem (২০১২) এই nuance ধরে।

৩ · MongoDB — document model

MongoDB-তে data থাকে document-এ — JSON-সদৃশ। অনেক document একসাথে থাকে collection-এ (relational-এর table-এর সমতুল্য)। schema flexible — একই collection-এ এক document-এ ১০টি field, অন্যটিতে ১৫টি — সমস্যা নেই।

Relational table — সরকারি office-এর form। প্রতিটি ঘর exact একটাই type-এর তথ্য নেয়। Document — ব্যক্তিগত খাতার page। আজ কেনাকাটার লিস্ট, কাল ডায়েরি, পরশু ঠিকানা — সব এক page-এ যেতে পারে। Flexibility বেশি, structure কম।

ভিতরে data BSONBSONBinary JSON — JSON-এর binary encoding। date, ObjectId, binary blob — JSON-এর চেয়ে বেশি type। size-efficient ও দ্রুত parse। হিসেবে save হয় — JSON-এর binary version, dates ও ObjectId-র মতো extra type সহ।

৪ · MongoDB CRUD — হাতে-কলমে

MongoDB shell
// Daraz-style product catalog
use daraz_demo

// একটি product insert
db.products.insertOne({
  sku: "DRZ-2025-1881",
  name: "Walton Refrigerator 350L",
  brand: "Walton",
  price: 52900,
  currency: "BDT",
  stock: 14,
  categories: ["appliances", "fridge"],
  specs: {
    capacity_l: 350,
    energy_rating: "5-star",
    warranty_years: 10
  },
  tags: ["bangladeshi-brand", "free-delivery"],
  created_at: new Date()
})

// একাধিক product
db.products.insertMany([
  { sku: "DRZ-1101", name: "PRAN Mango Drink 1L", price: 95, stock: 220 },
  { sku: "DRZ-1102", name: "RFL Plastic Chair", price: 1450, stock: 88 }
])

// Find — সব Walton brand
db.products.find({ brand: "Walton" })

// nested field — capacity 300L-এর বেশি
db.products.find({ "specs.capacity_l": { $gt: 300 } })

// update — stock কমানো
db.products.updateOne(
  { sku: "DRZ-2025-1881" },
  { $inc: { stock: -1 } }
)

// delete — stock 0 হলে remove (production-এ usually flag করেন)
db.products.deleteMany({ stock: 0 })

    
$gt, $lt, $in, $inc — MongoDB query operator। nested field-এ dot notation ("specs.capacity_l")। insertMany ordered by default — একটি ব্যর্থ হলে পরের গুলো বন্ধ হয়।

৫ · Aggregation Pipeline — MongoDB-র শক্তি

SQL-এর GROUP BY-র বিকল্প। data একটি pipeline-এর ভিতর দিয়ে যায় — প্রতিটি stage transform বা filter করে।

MongoDB shell
// প্রতিটি brand-এর গড় দাম, top 5
db.products.aggregate([
  { $match: { stock: { $gt: 0 } } },                // stage 1: filter
  { $group: {                                       // stage 2: group
      _id: "$brand",
      avg_price: { $avg: "$price" },
      total_stock: { $sum: "$stock" },
      product_count: { $sum: 1 }
  }},
  { $sort: { avg_price: -1 } },                     // stage 3: sort
  { $limit: 5 },                                    // stage 4: top 5
  { $project: {                                     // stage 5: shape output
      brand: "$_id",
      avg_price: { $round: ["$avg_price", 2] },
      product_count: 1,
      _id: 0
  }}
])

    
প্রতিটি stage-এর output পরের stage-এর input। $lookup stage দিয়ে collection-এর মধ্যে join-ও সম্ভব — কিন্তু performance relational JOIN-এর চেয়ে কম। তাই MongoDB-তে data সাধারণত embedded রাখা হয় (denormalize)।
NoSQL — চারটি family ও typical use-case Pick the model that matches your access pattern Document MongoDB, CouchDB {name:"...", price:.., specs:{...}} CMS, catalog Key-Value Redis, DynamoDB user:42 → {...} session:abc → ... Cache, session Wide-Column Cassandra, HBase row → many cols time-series friendly Logs, IoT, metrics Graph Neo4j, Neptune node + edge friend-of-friend Social, fraud কখন NoSQL জেতে — কখন হারে জেতে: variable schema জেতে: web-scale write জেতে: horizontal scale হারে: complex multi-JOIN হারে: financial txn হারে: ad-hoc analytics
NoSQL একটি family নয় — চারটি ভিন্ন paradigm। access pattern অনুযায়ী বাছুন; "trendy"-র জন্য নয়।

৬ · Index, sharding, replica set

  • Index: MongoDB-তেও B-tree index। db.products.createIndex({ brand: 1, price: -1 }) — compound, multi-key।
  • Replica set: primary + secondaries — automatic failover। ৩-node set production-এর minimum।
  • Sharding: data shard key দিয়ে multiple cluster-এ ভাগ। shard key বাছাই critical — ভুল বাছলে hot spot।
  • Change streams: oplog থেকে real-time event capture — CDC-র জন্য চমৎকার।

৭ · কখন NoSQL জেতে, কখন হারে

NoSQL জেতে যখন

১) Schema পরিবর্তনশীল (CMS, product catalog, IoT event)।
২) Hierarchical data — embedded subdocument-এ আদর্শ।
৩) Massive write throughput — horizontal scale।
৪) Geographically distributed users — multi-region replication।

NoSQL হারে যখন: অনেক table-এর মধ্যে complex JOIN। multi-document atomic transaction (যদিও MongoDB ৪.০-এ এসেছে — তবে slow)। ad-hoc analytics যেখানে predictable access pattern নেই। financial system যেখানে strict consistency দরকার। "We need NoSQL because we have lots of data" — সবচেয়ে বড় myth; relational DB-ও TB-scale handle করে।

৮ · Polyglot persistence — বাস্তব production

আধুনিক system একটি DB-তে আটকে থাকে না। Daraz-এ একই সময়ে: orders → PostgreSQL (ACID), product catalog → MongoDB/Elasticsearch (search), session → Redis (cache), event log → Kafka + Cassandra, graph (recommendation) → Neo4j। প্রতিটি tool যে কাজে শ্রেষ্ঠ — সে কাজে।

DE-র দায়িত্ব — এই DB-গুলোর মধ্যে data সঠিকভাবে sync রাখা। Change Data Capture (CDC), Kafka, Debezium এই কাজে আসে — পরের module-এ দেখব।

ভাবনার প্রশ্ন

প্রতিটি প্রশ্ন নিজে কিছুক্ষণ ভাবুন — তারপর "→ উত্তর" চাপুন।

প্র ০১ "MongoDB scales infinitely" — ২০১২-র এই hype থেকে অনেকে MongoDB বেছেছেন; পরে অনেক কোম্পানি Postgres-এ ফিরেছে। কেন? কী mistake হয়েছিল এবং কখন MongoDB সঠিক বাছাই?

২০১০-১৫ — MongoDB-র "golden era"। অনেক startup default-এ MongoDB বেছেছে। পরে — Uber, Tinder, Etsy-সহ অনেকে publicly Postgres-এ migrate করেছে। এটি technology hype cycle-এর classic case study।

কী ভুল হয়েছিল:

  • "Schema-less" misread: "schema নেই" মানে "schema design করা লাগবে না" — এটা ভুল। schema-এর responsibility application-এ চলে আসে; discipline ছাড়া chaos।
  • JOIN avoidance: embedded subdocument-এ data duplicate করতে হয়; product price বদলালে — সব order document update? Maintenance nightmare।
  • Transaction missing: ৪.০-এর আগে MongoDB-তে multi-document transaction ছিল না। financial বা inventory system-এ disaster।
  • Eventual consistency surprise: "I just wrote, why don't I see it?" — secondary থেকে read করলে।
  • Postgres ততদিনে JSONB এনেছে — flexibility-র জন্য আর MongoDB দরকার নেই।

MongoDB কখন সঠিক:

  • True document data — content management, IoT event, real-time analytics।
  • Schema rapidly evolving — early MVP।
  • Hierarchical data যা প্রায়ই unit হিসেবে read হয়।
  • Single-collection access pattern; cross-collection JOIN rare।
  • Geographically distributed write workload (sharding)।

উদাহরণ যেখানে MongoDB সফল:

  • The New York Times — content management।
  • EA — game state।
  • Forbes — article store।
  • Adobe Experience Manager।

মূল উপলব্ধি: Tool ভাল বা খারাপ না — fit ভাল বা খারাপ। "what does my data look like, how is it accessed" — এই দুটি প্রশ্ন আগে। DB পরে। বাংলাদেশ-এর startup-এ আমি প্রথমে Postgres recommend করি — JSONB-তে flexibility আছে — পরে scale-এ pain-point হলে selectively NoSQL যোগ করুন।

প্র ০২ Pathao-র জন্য একটি real-time location tracking system design করছেন — driver-দের location প্রতি ৫ সেকেন্ডে update। কোন NoSQL family ও কোন DB? কেন PostgreSQL এখানে দ্বিতীয় choice?

Real-time location tracking — NoSQL-এর textbook use-case। Pathao-র মতো প্রায় সব ride-sharing (Uber, Lyft, Grab) এই pattern follow করে।

Workload analysis:

  • ঢাকায় ৫০,০০০+ active driver, প্রতি ৫ sec → 10,000 writes/sec।
  • Read pattern: "এই rider-এর কাছাকাছি ৫ কিমির মধ্যে কত driver?"
  • Old data quickly stale — ১ মিনিট পরের location মূল্যহীন।
  • Strict ACID দরকার নেই — eventual consistency OK।

প্রাথমিক বাছাই:

  1. Redis (key-value): in-memory, sub-millisecond latency. Geo commands (GEOADD, GEORADIUS) built-in. driver_id → location TTL ৩০ sec। Pathao আসলে এটাই করে।
  2. MongoDB with 2dsphere index — ভাল, কিন্তু Redis-এর চেয়ে slow।
  3. Cassandra — write-heavy time-series log রাখার জন্য (historical replay), live tracking-এ অতিরিক্ত।

Production architecture:

  • Redis — current location (hot)।
  • Kafka — append every update (durability)।
  • Cassandra/Parquet on S3 — historical replay, ML training।
  • PostgreSQL — driver profile, trip records (cold, ACID)।

PostgreSQL কেন এখানে দ্বিতীয়:

  • Write-amplification: প্রতিটি update WAL-এ লেখা — disk I/O bottleneck।
  • VACUUM overhead: এত frequent update মানে dead tuple স্রোত।
  • ACID একটি liability এখানে — দরকার নেই, কিন্তু খরচ আছে।
  • Sub-ms latency দিতে কঠিন।

তবে: PostGIS (Postgres extension) geo query-তে চমৎকার — যদি আপনার scale মাঝারি হয় (১০০০ driver) — Postgres এক DB-তে সব handle করতে পারে। Pre-mature architecture-এর চেয়ে fewer DB ভাল।

মূল উপলব্ধি: "Best DB" বলে কিছু নেই — workload define করে। হট path-এর জন্য Redis, durability-র জন্য Kafka, analytics-এর জন্য warehouse — polyglot persistence।

প্র ০৩ MongoDB-তে "embed vs reference" — এই decision schema design-এর প্রাণ। কখন nested document রাখবেন, কখন আলাদা collection ও lookup? Daraz-এর order system-এ কীভাবে decide করবেন?

এটি MongoDB-র সবচেয়ে গুরুত্বপূর্ণ design decision। ভুল করলে — query slow, update painful।

Embed (nested document):

  • Data সবসময় parent-এর সাথে read হয়।
  • Update relatively rare বা parent-এর সাথে atomic।
  • Bounded growth — ১০০-এর বেশি item জমবে না।
  • One-to-one বা one-to-few relationship।

Reference (separate collection):

  • Data independently update হয়।
  • একই entity বহু parent-এ refer হয়।
  • Unbounded growth — হাজার + item জমতে পারে।
  • One-to-many বা many-to-many।

Daraz order system — case-by-case:

(ক) Order line items → embed

  • সবসময় order-এর সাথে read হয়।
  • Order create-এর পর item update বিরল।
  • সাধারণত ১-২০ item per order।
  • { order_id, items: [{ sku, qty, price_at_purchase }] }

(খ) Customer info → reference

  • Customer profile independently update হয় (address change, phone)।
  • একই customer-এর শত শত order।
  • Order-এ শুধু customer_id।

(গ) Product info — hybrid

  • Reference (product_id) + embed snapshot (name, price at purchase, image_url)।
  • কেন? — order-এ "purchase-time price" ফ্রিজ করা উচিত। পরে product price বদলালেও order history অপরিবর্তিত।
  • এটাকে বলে "denormalize for history"।

(ঘ) Order status history → embed array

  • Bounded (~১০ status)।
  • Order-এর সাথে read হয়।
  • status_history: [{ status, at, by }]

(ঙ) Reviews → separate collection

  • Unbounded — একটি product-এর হাজার review।
  • Review তার নিজের lifecycle (moderation, delete)।
  • Separate reviews collection, product_id + customer_id reference।

মূল ৬-step rule (MongoDB official):

  1. Cardinality? (one-to-one, few, many)
  2. Read frequency together?
  3. Independent updates?
  4. Bounded growth?
  5. Atomicity needed?
  6. Query simplicity worth duplication?

মূল উপলব্ধি: Relational-এ "normalize first"; MongoDB-তে "model around access pattern first"। Schema design আগে query design।

প্র ০৪ Grameenphone-এর IoT platform — কোটি কোটি SIM থেকে প্রতি মিনিটে usage event আসছে। Cassandra (wide-column) কেন এখানে MongoDB-র চেয়ে ভাল? কী trade-off?

Time-series ও massive-write workload — Cassandra-র জন্মস্থান। Facebook ২০০৮-এ inbox search-এর জন্য বানিয়েছিল।

Workload-এর বৈশিষ্ট্য:

  • ৪+ কোটি SIM, প্রতি SIM থেকে usage event (call, data, SMS) — দিনে multi-billion event।
  • Append-heavy: ৯৯% write, ১% read (mostly aggregate)।
  • Read pattern: "এই SIM-এর গত ২৪ ঘণ্টার data usage" — time-range query।
  • Multi-region: ঢাকা + চট্টগ্রাম DC fail-tolerance।

Cassandra কেন জেতে:

  • Linear write scalability: node যোগ করলে throughput proportional বাড়ে। MongoDB-তে sharding manual ও hot-spot risk।
  • LSM-tree storage: append-only writes, sequential disk I/O — extremely fast write।
  • Tunable consistency: ONE, QUORUM, ALL — query-by-query।
  • Multi-DC active-active: built-in।
  • Time-series friendly: partition key (sim_id) + clustering key (timestamp) — natural fit।
  • No single master: any node accepts writes।

MongoDB এখানে কেন কম উপযুক্ত:

  • Single primary per shard — write bottleneck।
  • Write amplification with B-tree index।
  • Scaling Cassandra-র চেয়ে jagged — operational pain।

Cassandra-র trade-offs:

  • Query model rigid: ad-hoc query সম্ভব না — partition key আগে ভাবতে হয়।
  • JOIN নেই: denormalize everything।
  • Eventual consistency: read-your-writes guarantee দিতে QUORUM read+write দরকার।
  • Operational complexity: Cassandra cluster tuning specialist কাজ — repair, compaction, gossip protocol।
  • Counter columns তুলনায় delicate।

Production stack — typical:

  • Edge → Kafka (buffer) → Cassandra (raw event)।
  • Spark batch → aggregated metrics → ClickHouse / Druid (BI dashboard)।
  • Hot lookup ("balance"): Redis।

মূল উপলব্ধি: Tools-এর deep specialization থাকে। MongoDB general-purpose; Cassandra time-series king। Grameenphone scale-এ specialization-এর benefit immense — operational complexity-এর খরচ সত্ত্বেও।

অনুশীলন

  1. Pipeline লিখুন: Daraz-এর orders collection (যেখানে items embed করা)। গত ৩০ দিনে প্রতিটি district-এ মোট sale revenue বের করুন, top ৫।
    db.orders.aggregate([
      { $match: {
          created_at: { $gte: new Date(Date.now() - 30*24*60*60*1000) },
          status: "delivered"
      }},
      { $unwind: "$items" },
      { $group: {
          _id: "$shipping.district",
          revenue: { $sum: { $multiply: ["$items.qty", "$items.price"] } },
          orders: { $addToSet: "$_id" }
      }},
      { $project: {
          district: "$_id",
          revenue: 1,
          order_count: { $size: "$orders" },
          _id: 0
      }},
      { $sort: { revenue: -1 } },
      { $limit: 5 }
    ])

    $unwind array-কে multiple document-এ ভাঙে। $addToSet distinct order count।

  2. Embed vs reference: একটি blogging platform-এ post-এ comment। প্রতিটি post-এ গড়ে ১০-৫০০০ comment। কী schema?

    Reference — separate comments collection। কারণ:

    • Unbounded growth — কিছু post-এ ৫০০০+ comment। MongoDB document size limit ১৬MB।
    • Comment independently update/delete হয়।
    • Pagination — সব comment একসাথে দরকার নেই।

    Schema: { post_id, author_id, body, created_at, parent_comment_id } + index {post_id: 1, created_at: -1}।

    Hot post-এ যদি ৫টি latest comment dashboard-এ দেখান — সেগুলো post document-এ embed snapshot রাখতে পারেন (read optimization)।

  3. CAP চিন্তা: বাংলাদেশের একটি ব্যাংকের core ledger system — CP নাকি AP? কেন?

    CP (Consistency + Partition tolerance, sacrificing availability)।

    • Money double-spent করা যাবে না — strict consistency obligatory।
    • Network partition হলে — better to refuse transaction than risk inconsistency।
    • "5 minute downtime" >> "1 wrong transaction"।
    • Bangladesh Bank regulatory compliance — auditable, consistent ledger।

    তাই — Oracle, PostgreSQL, SQL Server, IBM Db2 — সব CP RDBMS। Cassandra-র মতো AP-system এখানে অনুপযুক্ত।

    তবে — peripheral (notification, marketing) AP-system হতে পারে। Core ledger CP, সব সময়।

আরও পড়ুন · ABCL TECH-এ আপনার পরবর্তী পদক্ষেপ

MongoDB খেলতে চান? Browser-এ MongoDB Atlas ফ্রি tier (M0)-এ ৫১২MB cluster এক ক্লিকে। অথবা docker run -d -p 27017:27017 mongo:7 + mongosh। Google Colab-এ Python pymongo দিয়েও practice করতে পারেন।
পূর্ববর্তী পাঠ
পাঠ ০৮ · PostgreSQL