คู่มือผู้ใช้ MongoDB

แนวคิดพื้นฐาน

ฐานข้อมูล (Database)

ฐานข้อมูลคือคอนเทนเนอร์ระดับบนสุดของข้อมูลใน MongoDB แต่ละฐานข้อมูลมีคอลเลกชันและการตั้งค่าสิทธิ์ของตนเอง คุณสามารถสร้างหลายฐานข้อมูลใน MongoDB ได้ แต่ละฐานข้อมูลเป็นอิสระจากกัน

คอลเลกชัน (Collection)

คอลเลกชันคือกลุ่มของเอกสาร MongoDB คล้ายตารางในฐานข้อมูลเชิงสัมพันธ์ เอกสารในคอลเลกชันหนึ่งอาจมีฟิลด์ที่แตกต่างกัน ทำให้คอลเลกชันมีความยืดหยุ่นสูง ไม่เหมือนฐานข้อมูลเชิงสัมพันธ์ คอลเลกชันไม่บังคับให้มีสคีมาตายตัวและกำหนดไว้ล่วงหน้า

เอกสาร (Document)

เอกสารคือหน่วยข้อมูลพื้นฐานใน MongoDB ประกอบด้วยคู่ของฟิลด์และค่า เอกสารคล้ายอ็อบเจกต์ JSON และถูกจัดเก็บในรูปแบบ BSON (Binary JSON)

BSON คือการแทนค่าของเอกสาร JSON ในรูปแบบไบนารี ซึ่งรองรับชนิดข้อมูลเพิ่มเติม ขนาดสูงสุดของเอกสารคือ 16 MB

การเชื่อมต่อกับ MongoDB

เชื่อมต่อฐานข้อมูลในเครื่องด้วย mongosh

mongosh

เชื่อมต่อฐานข้อมูลระยะไกล

mongosh "mongodb://hostname:port"

เชื่อมต่อโดยใช้สตริงการเชื่อมต่อพร้อมการยืนยันตัวตน

mongosh "mongodb://username:password@hostname:port/database?authSource=admin"

เชื่อมต่อโดยใช้ URI

mongosh "mongodb://localhost:27017,mongodb://localhost:27018/?replicaSet=myReplSet"

การดำเนินการกับฐานข้อมูล

ดูรายการฐานข้อมูล

show dbs

สลับ/สร้างฐานข้อมูล

use mydatabase

หมายเหตุ: เมื่อสลับฐานข้อมูลด้วยคำสั่ง use หากฐานข้อมูลนั้นไม่มีอยู่ MongoDB จะสร้างขึ้น แต่จะยังไม่ถูกสร้างจริงจนกว่าคุณจะแทรกเอกสาร

ดูข้อมูลของฐานข้อมูลปัจจุบัน

db.stats()

ลบฐานข้อมูล

db.dropDatabase()

การดำเนินการกับคอลเลกชัน

ดูรายการคอลเลกชัน

show collections

สร้างคอลเลกชัน

db.createCollection("mycollection")

สร้างคอลเลกชันพร้อมตัวเลือก

db.createCollection("mycollection", {
  capped: true,
  size: 1000000,
  max: 100
})

ลบคอลเลกชัน

db.mycollection.drop()

ดูสถิติของคอลเลกชัน

db.mycollection.stats()

การแทรกเอกสาร

MongoDB มีวิธีการดังต่อไปนี้สำหรับแทรกเอกสารเข้าคอลเลกชัน:

แทรกเอกสารเดียว

db.users.insertOne({
  name: "John",
  age: 30,
  email: "[email protected]",
  address: {
    city: "New York",
    street: "Main Street"
  },
  hobbies: ["basketball", "swimming"]
})

แทรกหลายเอกสาร

db.users.insertMany([
  { name: "Jane", age: 25, city: "Los Angeles" },
  { name: "Bob", age: 35, city: "Chicago" },
  { name: "Alice", age: 28, city: "San Francisco" }
])

แทรกเอกสาร (เลิกใช้แล้วแต่ยังใช้ได้)

db.users.insert({
  name: "David",
  age: 32
})

ดูผลลัพธ์การแทรก

# View inserted document ID
db.users.insertOne({ name: "Test" })
# Returns: { acknowledged: true, insertedId: ObjectId("...") }

การค้นหาเอกสาร

ค้นหาเอกสารทั้งหมด

db.users.find()

คำสั่งนี้เทียบเท่ากับ SELECT * FROM users ใน SQL

ค้นหาเอกสารเดียว

db.users.findOne()

ค้นหาด้วยเงื่อนไข

# Equality query
db.users.find({ age: 30 })

# Not equal query
db.users.find({ age: { $ne: 30 } })

# Greater than query
db.users.find({ age: { $gt: 25 } })

# Greater than or equal query
db.users.find({ age: { $gte: 25 } })

# Less than query
db.users.find({ age: { $lt: 30 } })

# Less than or equal query
db.users.find({ age: { $lte: 30 } })

# Range query
db.users.find({ age: { $gte: 20, $lte: 30 } })

ตัวดำเนินการเชิงตรรกะ

# AND (default)
db.users.find({ age: { $gte: 25 }, name: "Jane" })

# OR
db.users.find({ $or: [{ age: { $gte: 30 } }, { name: "Bob" }] })

# NOR (neither nor)
db.users.find({ $nor: [{ age: { $lt: 20 } }, { city: "New York" }] })

# NOT
db.users.find({ age: { $not: { $gte: 25 } } })

การค้นหาในอาร์เรย์

# Array contains element
db.users.find({ hobbies: "basketball" })

# Array contains all elements
db.users.find({ hobbies: { $all: ["basketball", "swimming"] } })

# Array length
db.users.find({ hobbies: { $size: 2 } })

# Array element at specific position
db.users.find({ "hobbies.0": "basketball" })

# Array element matching condition
db.users.find({ hobbies: { $elemMatch: { $eq: "basketball" } } })

การค้นหาเอกสารที่ซ้อนกัน

# Nested document field query
db.users.find({ "address.city": "New York" })

# Complete nested document match
db.users.find({ address: { city: "New York", street: "Main Street" } })

การเลือกฟิลด์ (Projection)

# Return only name and email fields
db.users.find({ age: 30 }, { name: 1, email: 1 })

# Exclude a field
db.users.find({}, { age: 0 })

# Return all fields except _id
db.users.find({}, { _id: 0 })

การเรียงลำดับ

# Sort by age ascending
db.users.find().sort({ age: 1 })

# Sort by age descending
db.users.find().sort({ age: -1 })

# Multi-field sort
db.users.find().sort({ age: -1, name: 1 })

Limit และ Skip

# Return first 5 documents
db.users.find().limit(5)

# Skip first 10 documents, return next 5 (pagination)
db.users.find().skip(10).limit(5)

# Count documents
db.users.countDocuments({ age: { $gte: 25 } })

# Estimate collection document count (fast but may be inaccurate)
db.users.estimatedDocumentCount()

การดำเนินการกับเคอร์เซอร์

# Use cursor
var cursor = db.users.find()
while (cursor.hasNext()) {
  printjson(cursor.next())
}

# forEach iteration
db.users.find().forEach(function(doc) {
  print("Name: " + doc.name)
})

การอัปเดตเอกสาร

อัปเดตเอกสารเดียว

db.users.updateOne(
  { name: "John" },
  { $set: { age: 31 } }
)

อัปเดตหลายเอกสาร

db.users.updateMany(
  { age: { $lt: 30 } },
  { $set: { status: "young" } }
)

แทนที่เอกสาร

db.users.replaceOne(
  { name: "John" },
  { name: "John", age: 32, email: "[email protected]", city: "Boston" }
)

ตัวดำเนินการในการอัปเดต

# $set - Set field value
db.users.updateOne({ name: "Jane" }, { $set: { age: 26 } })

# $unset - Remove field
db.users.updateOne({ name: "Jane" }, { $unset: { email: "" } })

# $inc - Increment/decrement
db.users.updateOne({ name: "Jane" }, { $inc: { age: 1 } })
db.users.updateOne({ name: "Jane" }, { $inc: { age: -1 } })

# $rename - Rename field
db.users.updateOne({ name: "Jane" }, { $rename: { "name": "fullname" } })

# $mul - Multiply
db.users.updateOne({ name: "Jane" }, { $mul: { age: 2 } })

# $min - Set minimum value
db.users.updateOne({ name: "Jane" }, { $min: { age: 20 } })

# $max - Set maximum value
db.users.updateOne({ name: "Jane" }, { $max: { age: 40 } })

# $push - Add element to array
db.users.updateOne({ name: "Jane" }, { $push: { hobbies: "running" } })

# $pull - Remove matching elements from array
db.users.updateOne({ name: "Jane" }, { $pull: { hobbies: "swimming" } })

# $addToSet - Add element to array (no duplicates)
db.users.updateOne({ name: "Jane" }, { $addToSet: { hobbies: "basketball" } })

# $pop - Remove first or last element from array
db.users.updateOne({ name: "Jane" }, { $pop: { hobbies: 1 } })

การดำเนินการแบบ Upsert

# Insert if not exists, update if exists
db.users.updateOne(
  { name: "New User" },
  { $set: { age: 25, city: "Seattle" } },
  { upsert: true }
)

การลบเอกสาร

ลบเอกสารเดียว

db.users.deleteOne({ name: "John" })

ลบหลายเอกสาร

db.users.deleteMany({ age: { $lt: 20 } })

ลบเอกสารทั้งหมด

db.users.deleteMany({})

สายการประมวลผลแบบรวม (Aggregation Pipeline)

สายการประมวลผลแบบรวมเป็นหนึ่งในคุณสมบัติที่ทรงพลังที่สุดของ MongoDB ใช้สำหรับประมวลผลสตรีมข้อมูลและทำการแปลงข้อมูลและวิเคราะห์ที่ซับซ้อน

ไวยากรณ์พื้นฐาน

db.collection.aggregate([
  { $stage1: { ... } },
  { $stage2: { ... } },
  ...
])

ขั้นตอนการรวมที่พบบ่อย

$match - กรองเอกสาร

db.users.aggregate([
  { $match: { age: { $gte: 25 } } }
])

$project - การเลือกฟิลด์

db.users.aggregate([
  { $project: { _id: 0, name: 1, age: 1 } }
])

$group - การจัดกลุ่ม

# Count users by age
db.users.aggregate([
  { $group: { _id: "$age", count: { $sum: 1 } } }
])

# Calculate average age
db.users.aggregate([
  { $group: { _id: null, avgAge: { $avg: "$age" } } }
])

# Group and collect names
db.users.aggregate([
  { $group: { _id: "$city", users: { $push: "$name" } } }
])

$sort - การเรียงลำดับ

db.users.aggregate([
  { $sort: { age: -1, name: 1 } }
])

$limit - จำกัดจำนวน

db.users.aggregate([
  { $limit: 5 }
])

$skip - ข้ามเอกสาร

db.users.aggregate([
  { $skip: 10 },
  { $limit: 5 }
])

$unwind - แยกอาร์เรย์

db.users.aggregate([
  { $unwind: "$hobbies" }
])

$lookup - เข้าร่วมคอลเลกชัน

# Assuming two collections: orders and products
db.orders.aggregate([
  {
    $lookup: {
      from: "products",
      localField: "productId",
      foreignField: "_id",
      as: "productDetails"
    }
  }
])

ตัวดำเนินการในการรวม

ตัวดำเนินการทางคณิตศาสตร์

db.sales.aggregate([
  {
    $project: {
      total: { $add: ["$price", "$tax"] },
      discount: { $multiply: ["$price", 0.1] }
    }
  }
])

ตัวดำเนินการด้านข้อความ

db.users.aggregate([
  {
    $project: {
      fullName: { $concat: ["$firstName", " ", "$lastName"] },
      upperName: { $toUpper: "$name" }
    }
  }
])

ตัวดำเนินการด้านวันที่

db.users.aggregate([
  {
    $project: {
      year: { $year: "$birthdate" },
      month: { $month: "$birthdate" },
      day: { $dayOfMonth: "$birthdate" }
    }
  }
])

ตัวอย่างที่สมบูรณ์

# Find the top three airlines with the most direct flights out of PDX
db.routes.aggregate([
  {
    $match: {
      "src_airport": "PDX",
      "stops": 0
    }
  },
  {
    $group: {
      _id: "$airline.name",
      count: { $sum: 1 }
    }
  },
  {
    $sort: { count: -1 }
  },
  {
    $limit: 3
  }
])

ดัชนี

ดัชนีรองรับการดำเนินการค้นหาอย่างมีประสิทธิภาพใน MongoDB หากไม่มีดัชนี MongoDB ต้องสแกนเอกสารทุกเอกสารในคอลเลกชันเพื่อส่งกลับผลลัพธ์การค้นหา

การสร้างดัชนี

# Single field index
db.users.createIndex({ name: 1 })

# Descending index
db.users.createIndex({ age: -1 })

# Compound index
db.users.createIndex({ age: 1, name: 1 })

# Unique index
db.users.createIndex({ email: 1 }, { unique: true })

# Text index
db.users.createIndex({ description: "text" })

# Multikey index (array field)
db.users.createIndex({ hobbies: 1 })

# Geospatial index
db.locations.createIndex({ location: "2dsphere" })

# Hashed index
db.users.createIndex({ _id: "hashed" })

การดูดัชนี

# View all indexes on a collection
db.users.getIndexes()

# View index size
db.users.totalIndexSize()

การลบดัชนี

# Drop specified index
db.users.dropIndex("name_1")

# Drop all indexes (except _id index)
db.users.dropIndexes()

# Drop text index
db.users.dropIndex("description_text")

คุณสมบัติของดัชนี

# Sparse index (only indexes non-null values)
db.users.createIndex({ email: 1 }, { sparse: true })

# Partial index
db.users.createIndex(
  { email: 1 },
  { partialFilterExpression: { email: { $exists: true } } }
)

# TTL index (automatic expiration)
db.sessions.createIndex(
  { createdAt: 1 },
  { expireAfterSeconds: 3600 }
)

ข้อเสนอแนะด้านกลยุทธ์การทำดัชนี

  • สร้างดัชนีบนฟิลด์ที่มักถูกใช้ในเงื่อนไขการค้นหา
  • ลำดับของฟิลด์ในดัชนีแบบผสมมีความสำคัญ: วางฟิลด์ที่ตรงกันแบบเต็มที่สุดไว้ก่อน และฟิลด์ที่ใช้ค้นหาแบบช่วงไว้ท้ายสุด
  • หลีกเลี่ยงการสร้างดัชนีจำนวนมากเกินไปบนคอลเลกชันที่มีความถี่ในการเขียนสูง
  • ใช้ explain() เพื่อวิเคราะห์ประสิทธิภาพการค้นหา

การวิเคราะห์การค้นหา

# Analyze query
db.users.find({ age: 25 }).explain()

# Analyze execution plan
db.users.find({ age: { $gte: 25 } }).sort({ name: 1 }).explain("executionStats")

การดำเนินการกับ Replica Set

Replica set คือกลุ่มของอินสแตนซ์ MongoDB ที่เก็บชุดข้อมูลเดียวกัน ให้ความซ้ำซ้อนและความพร้อมใช้งานสูง

เริ่มต้น Replica Set

rs.initiate()

ดูสถานะ Replica Set

rs.status()

ดูการตั้งค่า Replica Set

rs.conf()

เพิ่มสมาชิกรอง (Secondary)

rs.add("hostname:27017")

เพิ่ม Arbiter

rs.addArb("hostname:27017")

ลบสมาชิก

rs.remove("hostname:27017")

การเลือกตั้งใน Replica Set

เมื่อ primary ใช้งานไม่ได้ replica set จะดำเนินการเลือกตั้งโดยอัตโนมัติ คุณสามารถกระตุ้นการเลือกตั้งได้ด้วย:

# Force current node to become primary (use in specific situations)
rs.stepDown()

Read Preference

# Read from primary (default)
db.getMongo().setReadPref("primary")

# Read from secondary
db.getMongo().setReadPref("secondary")

# Read from nearest node
db.getMongo().setReadPref("nearest")

การดำเนินการกับ Sharding

Sharding คือแนวทางของ MongoDB ในการขยายขนาดแนวนอน โดยกระจายข้อมูลไปยังเซิร์ฟเวอร์หลายเครื่อง

เปิดใช้งาน Sharding

sh.enableSharding("mydatabase")

แบ่งข้อมูลของคอลเลกชัน

sh.shardCollection("mydatabase.mycollection", { _id: 1 })

ดูสถานะ Sharding

sh.status()

เพิ่ม Shard

sh.addShard("shard_replica_set/hostname:27017")

การนำเข้าและส่งออกข้อมูล

การใช้ mongodump และ mongorestore

ส่งออกข้อมูล

# Export entire database
mongodump --db=mydatabase --out=/backup

# Export specific collection
mongodump --db=mydatabase --collection=users --out=/backup

# Export with compression
mongodump --db=mydatabase --gzip --out=/backup

นำเข้าข้อมูล

# Restore entire database
mongorestore --db=mydatabase /backup/mydatabase

# Restore specific collection
mongorestore --db=mydatabase --collection=users /backup/mydatabase/users.bson

# Restore with compression
mongorestore --db=mydatabase --gzip /backup/mongodb

การใช้ mongoexport และ mongoimport

ส่งออกเป็น JSON

# Export as JSON
mongoexport --db=mydatabase --collection=users --out=users.json

# Export as JSON array
mongoexport --db=mydatabase --collection=users --out=users.json --jsonArray

# Export CSV
mongoexport --db=mydatabase --collection=users --out=users.csv --fields=name,age,email

นำเข้าจาก JSON

# Import from JSON
mongoimport --db=mydatabase --collection=users --file=users.json

# Import from JSON array
mongoimport --db=mydatabase --collection=users --file=users.json --jsonArray

# Import from CSV
mongoimport --db=mydatabase --collection=users --file=users.csv --headerline

คำสั่งดูแลระบบที่พบบ่อย

ดูสถานะเซิร์ฟเวอร์

db.serverStatus()

ดูสถานะฐานข้อมูลปัจจุบัน

db.stats()

ดูสถิติของคอลเลกชัน

db.users.stats()

ดูการดำเนินการปัจจุบัน

db.currentOp()

ดูคิวรีที่ช้า

# View recent slow queries
db.system.profile.find().sort({ ts: -1 }).limit(10)

บังคับปิดฐานข้อมูล

# Use in emergencies only
db.adminCommand({ shutdown: 1 })

การดำเนินการกับธุรกรรม

MongoDB 4.0 ขึ้นไปรองรับธุรกรรมแบบหลายเอกสาร

ธุรกรรมพื้นฐาน

session = db.getMongo().startSession()
session.startTransaction({ readConcern: { level: "snapshot" }, writeConcern: { w: "majority" } })

try {
  session.getDatabase("mydb").accounts.updateOne(
    { accountId: 1 },
    { $inc: { balance: -100 } }
  )
  session.getDatabase("mydb").accounts.updateOne(
    { accountId: 2 },
    { $inc: { balance: 100 } }
  )
  session.commitTransaction()
} catch (error) {
  session.abortTransaction()
  throw error
} finally {
  session.endSession()
}

Change Streams

Change streams ช่วยให้แอปพลิเคชันรับฟังการเปลี่ยนแปลงข้อมูลแบบเรียลไทม์ได้

# Listen for collection changes
var changeStream = db.users.watch()
while (changeStream.hasNext()) {
  printjson(changeStream.next())
}

GridFS

GridFS ใช้จัดเก็บไฟล์ขนาดใหญ่ที่เกินขนาดจำกัด 16 MB

# Upload file
mongofiles put myfile.txt

# List files
mongofiles list

# Download file
mongofiles get myfile.txt

# Delete file
mongofiles delete myfile.txt