0Pricing
MongoDB Academy · บทเรียน

ฐานข้อมูล คอลเลกชัน และเนมสเปซ

ผู้เรียนจะสร้างฐานข้อมูล เพิ่มคอลเลกชัน และเข้าใจว่า MongoDB จัดระเบียบข้อมูลในระดับเนมสเปซอย่างไร

ฐานข้อมูล คอลเลกชัน และเนมสเปซ เป็นบทเรียน MongoDB Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน MongoDB Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส MongoDB Academy มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

MongoDB's Three-Level Hierarchy

MongoDB nests data in three levels: Database, Collection, Document. It mirrors SQL's database, table, row — and one server can hold many of each.

What Is a Namespace?

A namespace names a collection by combining database and collection with a dot, like myapp.users. You'll see this notation in logs and explain output.

// Namespace: database.collection
// 'shop' database, 'products' collection:
use shop
db.products.find({})
// MongoDB internally refers to this as 'shop.products'

// You can also reference it explicitly:
db.getSiblingDB('shop').getCollection('products').find({})

Switching and Creating Databases

In mongosh, use switches databases. There's no CREATE DATABASE — MongoDB makes one lazily, the moment you insert your first document. The code shows it.

// Switch to (or create) a database
use myNewApp
// 'myNewApp' doesn't exist yet - no error, but not visible in 'show dbs'

// Insert a document to materialize the database
db.users.insertOne({ name: 'Alice' });

// Now 'myNewApp' appears:
show dbs
// admin     0.000GB
// local     0.000GB
// myNewApp  0.000GB

System Databases: admin, local, config

MongoDB keeps three system databases: admin for users and roles, local for replication data, and config for sharded-cluster metadata. Good to recognize, not to touch.

// View all databases on the server
show dbs
// admin   0.000GB
// config  0.000GB
// local   0.004GB
// shop    0.012GB
// myapp   0.008GB

// List databases programmatically
db.adminCommand({ listDatabases: 1 });

Creating Collections Explicitly

Use createCollection when you need special options up front — capped, time-series, clustered, or a schema validator. The code creates one with validation rules.

// Create a collection with a JSON Schema validator
db.createCollection('products', {
  validator: {
    $jsonSchema: {
      bsonType: 'object',
      required: ['name', 'price'],
      properties: {
        name:  { bsonType: 'string' },
        price: { bsonType: 'number', minimum: 0 }
      }
    }
  }
});

Listing and Inspecting Collections

A few commands let you explore your database: list collections, get detailed info, and check storage stats. show collections is the quick one. The code shows more.

use shop

show collections
// orders
// products
// users

db.getCollectionInfos();
// Returns array of {name, type, options, idIndex} per collection

db.orders.stats().count;
// 15234

db.orders.totalIndexSize();
// 2359296 (bytes)

Renaming and Dropping Collections

You can rename a collection instantly, or drop one to delete it for good. Dropping is permanent — there's no recycle bin, so back up first in production.

// Rename a collection
db.oldUsers.renameCollection('users');
// { ok: 1 }

// Drop a collection - IRREVERSIBLE
db.tempData.drop();
// true

// Drop the entire database - EXTREMELY DANGEROUS
// db.dropDatabase();
// Use only in development or with full backup

Multi-Tenancy With Databases

For SaaS apps, multi-tenancy can mean a database per customer for strong isolation, or one shared collection filtered by a tenantId field. The code shows both.

// Option 1: Database-per-tenant
const db = client.db('tenant_' + tenantId);
db.users.find({});
// Each tenant has completely isolated data

// Option 2: Shared collection with tenantId field
const db = client.db('saas_app');
db.users.find({ tenantId: tenantId });
// All tenants share one collection, filtered by tenantId

Collection Naming Best Practices

A few naming habits prevent headaches: stay consistent, use plural nouns like users, and avoid special characters. Good naming conventions make code easier to read.

// Good collection names
db.users.find({});
db.order_items.find({});
db.productCategories.find({});

// Avoid these
db['$sales'].find({});        // $ prefix causes issues
db['system.logs'].find({});   // reserved prefix
db['my.collection'].find({}); // dot in name causes confusion

The WiredTiger Storage Engine

MongoDB's default storage engine is WiredTiger. It allows many writes at once without blocking, compresses data on disk, and journals writes so crashes don't lose data.

// Check current storage engine
db.serverStatus().storageEngine;
// { name: 'wiredTiger', supportsCommittedReads: true, ... }

// Collection stats show compression savings
db.orders.stats();
// storageSize: 2097152 (compressed on disk)
// size: 8388608 (uncompressed logical size)

Understanding the Oplog

The oplog is a special log of every write in a replica set. Secondaries replay it to stay in sync, and it also powers MongoDB's live Change Streams.

// Inspect oplog in mongosh (replica set members only)
use local
db.oplog.rs.find().sort({ $natural: -1 }).limit(3);
// { op: 'i', ns: 'shop.orders', o: { _id: ..., ... } }
// op: 'i'=insert, 'u'=update, 'd'=delete, 'c'=command

Quick Check

Test your understanding of MongoDB & NoSQL Databases concepts from this lesson.

Lesson Recap

You learned MongoDB organizes data as Database, Collection, Document, that databases are created lazily, and that WiredTiger powers storage. Next: the mongosh shell.

คำถามที่พบบ่อย

บทเรียน “ฐานข้อมูล คอลเลกชัน และเนมสเปซ” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “ฐานข้อมูล คอลเลกชัน และเนมสเปซ” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส MongoDB Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส MongoDB Academy มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “ฐานข้อมูล คอลเลกชัน และเนมสเปซ”

ผู้เรียนจะสร้างฐานข้อมูล เพิ่มคอลเลกชัน และเข้าใจว่า MongoDB จัดระเบียบข้อมูลในระดับเนมสเปซอย่างไร คุณปฏิบัติ MongoDB Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน MongoDB Academy หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน MongoDB Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน

บทเรียน “ฐานข้อมูล คอลเลกชัน และเนมสเปซ” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน MongoDB Academy นี้ได้ไหม

ได้ บทเรียน MongoDB Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. เอกสาร BSON คืออะไร
  2. คอลเลกชันเทียบกับตาราง SQL
  3. ฐานข้อมูล คอลเลกชัน และเนมสเปซ
  4. พื้นฐานเชลล์ mongosh
← กลับไปที่ MongoDB Academy