Skip to content
← All Skills
🍃

MongoDB

Data & MessagingOfficial Site ›

Document database — flexible schema, aggregation pipeline, horizontal scaling

What I Can Do

  • ออกแบบ document schema ที่เหมาะกับ access patterns
  • เขียน aggregation pipelines สำหรับ complex queries
  • Implement indexing strategy สำหรับ query performance
  • จัดการ replication และ sharding สำหรับ high availability
  • Migrate ระหว่าง schema versions โดยไม่ downtime

Commands I Use Daily

bash
# เข้า MongoDB shell
mongosh

# เลือก database
use mydb

# basic CRUD
db.users.insertOne({ name: "John", age: 30 })
db.users.find({ age: { $gte: 25 } })
db.users.updateOne({ _id: id }, { $set: { age: 31 } })
db.users.deleteOne({ _id: id })

# ดู indexes
db.users.getIndexes()

# explain query plan
db.users.find({ name: "John" }).explain("executionStats")

# server status
db.serverStatus()

# collection stats
db.users.stats()

Document Model

MongoDB เก็บข้อมูลเป็น BSON documents (Binary JSON) — flexible schema, แต่ละ document ใน collection เดียวกันมี fields ต่างกันได้ เหมาะกับ data ที่มี varying structure, nested objects, arrays

Collections & Databases

  • Database — group ของ collections, use mydb สร้าง/เลือก database
  • Collection — group ของ documents (เหมือน table ใน SQL แต่ schema-free)
  • _id field เป็น primary key อัตโนมัติ (ObjectId by default)

CRUD Operations

  • insertOne/insertMany — สร้าง documents
  • find/findOne — อ่าน, ใช้ query filters
  • updateOne/updateMany — แก้ไข, ใช้ update operators ($set, $inc, $push)
  • deleteOne/deleteMany — ลบ
  • bulkWrite — batch operations สำหรับ performance

Query Operators

  • Comparison$eq, $gt, $gte, $lt, $lte, $ne, $in, $nin
  • Logical$and, $or, $not, $nor
  • Element$exists, $type
  • Array$elemMatch, $size, $all
  • Regex{ name: { $regex: /^John/i } }

Update Operators

  • $set — set field value, $unset — remove field
  • $inc — increment number, $mul — multiply
  • $push / $pull — add/remove from array
  • $addToSet — add to array only if not exists
  • $rename — rename field
  • Array positional operator $ สำหรับ update specific element

Projection & Sorting

  • Projection — เลือก fields ที่จะ return: find({}, { name: 1, age: 1, _id: 0 })
  • sort({ age: -1 }) — เรียงลำดับ (1 = ascending, -1 = descending)
  • limit(10), skip(20) — pagination (แต่ skip-based pagination ช้าเมื่อ offset ใหญ่)

Indexing Basics

Index ช่วยให้ query เร็วขึ้น — createIndex({ field: 1 }) สร้าง ascending index, ไม่มี index = collection scan (ช้ามาก), ทุก collection มี _id index อัตโนมัติ, ใช้ explain() ตรวจว่า query ใช้ index หรือไม่

Compound & Multikey Indexes

  • Compound indexcreateIndex({ field1: 1, field2: -1 }) ครอบคลุม queries ที่ filter/sort หลาย fields, ลำดับ fields สำคัญ (ESR rule: Equality, Sort, Range)
  • Multikey index — auto-created เมื่อ index field เป็น array, index ทุก element

Aggregation Pipeline

db.collection.aggregate([stages]) — chain ของ data transformations:

  • $match — filter documents
  • $group — group by field, ใช้ accumulators ($sum, $avg, $count)
  • $project — reshape documents
  • $sort, $limit, $skip — ordering/pagination
  • $lookup — left outer join กับ collection อื่น

$lookup (Joins)

text
{ $lookup: { from: "orders", localField: "_id", foreignField: "userId", as: "orders" } }

ทำ left outer join — ได้ array ของ matching documents, ใช้ร่วมกับ $unwind เพื่อ flatten, pipeline variant สำหรับ complex join conditions

Schema Design Patterns

  • Embedding — nested documents ใน document เดียว (1-to-few, data ที่อ่านด้วยกัน)
  • Referencing — เก็บ _id reference ไปยัง document อื่น (1-to-many, many-to-many)
  • Bucket pattern — group time-series data เป็น buckets
  • Outlier pattern — handle documents ที่มี array ใหญ่ผิดปกติ

Schema Validation

createCollection หรือ collMod ด้วย validator — กำหนด JSON Schema rules สำหรับ documents, enforce required fields, types, patterns ที่ application level ไม่ครอบคลุม

Transactions

MongoDB 4.0+ รองรับ multi-document transactions — session.withTransaction(async () => { ... }) ACID guarantees ข้าม documents/collections ใช้เมื่อต้องการ atomicity ข้ามหลาย operations แต่มี performance overhead

Replication (Replica Set)

Replica set = primary + secondaries — primary รับ writes, secondaries replicate asynchronously, automatic failover ถ้า primary ล่ม elect secondary ขึ้นเป็น primary ใหม่, read preference config สำหรับ read scaling

Change Streams

collection.watch() — real-time notifications เมื่อ data เปลี่ยน, ใช้สำหรับ event-driven architectures, cache invalidation, sync ไปยัง external systems, ต้องใช้กับ replica set

Text Search & Atlas Search

  • Text indexcreateIndex({ content: "text" }) + $text operator สำหรับ basic full-text search
  • Atlas Search — Lucene-based, รองรับ fuzzy matching, autocomplete, faceted search
  • สำหรับ complex search ใช้ Atlas Search หรือ Elasticsearch แทน basic text index

Sharding

Horizontal scaling — distribute data ข้าม shards ด้วย shard key, sh.shardCollection("db.collection", { field: 1 }) เลือก shard key ที่มี high cardinality และ distribute writes evenly, ระวัง scatter-gather queries

Time-Series Collections

MongoDB 5.0+ — createCollection("metrics", { timeseries: { timeField: "timestamp" } }) optimized storage สำหรับ time-series data, automatic bucketing, efficient compression, built-in window functions

Performance Tuning

  • ใช้ explain("executionStats") วิเคราะห์ query plan
  • สร้าง indexes ตาม query patterns (ESR rule)
  • Avoid $regex ที่ไม่ anchored, large $in arrays
  • Connection pooling, read preference สำหรับ read-heavy workloads
  • currentOp() หา slow queries, db.setProfilingLevel(1) log slow queries

Related Skills

  • Go — backend services ที่ใช้ MongoDB เป็น data store
  • PostgreSQL — relational alternative สำหรับ structured data
  • Redis — caching layer ด้านหน้า MongoDB
  • Docker — run MongoDB ใน container สำหรับ development