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

คอลเลกชันเทียบกับตาราง SQL

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

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

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

Tables vs Collections at a Glance

SQL's basic unit is the table, where every row has identical columns. MongoDB's is the collection — a group of documents that can each differ.

Fixed Schema: The SQL Way

SQL needs a fixed schema defined before any data goes in, and changing it later can rebuild the whole table. Rigid, but predictable and storage-efficient.

-- SQL table: schema defined upfront, rigid
CREATE TABLE users (
  id         SERIAL PRIMARY KEY,
  name       VARCHAR(100) NOT NULL,
  email      VARCHAR(200) UNIQUE NOT NULL,
  age        INT,
  created_at TIMESTAMP DEFAULT NOW()
);
-- Every row must have exactly these columns

Flexible Schema: The MongoDB Way

A MongoDB collection appears the moment you insert — no schema needed. This flexible schema is great for prototyping, but your code must handle missing fields.

// No schema definition needed - collection created on first insert
db.users.insertOne({ name: 'Alice', email: 'alice@test.com', age: 30 });

// Next insert can have completely different fields
db.users.insertOne({ name: 'Bob', email: 'bob@test.com', company: 'Acme', role: 'admin' });

// Both documents live in the same 'users' collection

Schema vs Schema-Less: The Trade-Off

Neither wins outright. Fixed schemas guard against bad data; flexible ones let you move fast. MongoDB's JSON Schema validation gives you optional middle ground.

Normalization vs Denormalization

SQL favors normalization — splitting data across tables. MongoDB favors denormalization — embedding related data together, so you read it all in one go without JOINs.

// SQL normalized: address in separate table
// SELECT u.name, a.city FROM users u JOIN addresses a ON a.user_id = u.id

// MongoDB denormalized: address embedded in user document
{
  _id: ObjectId('...'),
  name: 'Alice',
  address: { city: 'London', zip: 'EC1A' }   // no JOIN needed
}

Creating Collections Explicitly

Collections appear automatically, but createCollection lets you set options up front — like a capped collection for logs or a validator. The code shows one.

// Create a capped collection explicitly
db.createCollection('appLogs', {
  capped: true,
  size: 10485760,   // 10 MB maximum size
  max: 50000        // optional: max 50,000 documents
});
// When full, oldest documents are automatically removed

Listing and Dropping Collections

A few handy commands list, count, and drop collections. To empty one without deleting it, use deleteMany — there's no TRUNCATE in MongoDB. The code shows them.

// Useful collection management commands in mongosh
db.getCollectionNames();
// ['users', 'orders', 'products']

db.users.countDocuments({});
// 4823

db.users.stats().storageSize;
// 2097152 (bytes)

// Delete all documents but keep the collection:
db.users.deleteMany({});
// { acknowledged: true, deletedCount: 4823 }

The _id Field and Primary Keys

Every collection has _id as its primary key, with an automatic unique index. You can supply your own _id — like a product SKU — as long as it's unique.

// Custom _id values
db.products.insertOne({
  _id: 'SKU-HEADPHONES-BLK-42',   // string _id
  name: 'Wireless Headphones Black',
  price: 79.99
});

// Lookup by custom _id is O(log n) via the _id index
db.products.findOne({ _id: 'SKU-HEADPHONES-BLK-42' });

Index Structure Differences

Both SQL and MongoDB use B-tree indexes, but MongoDB can index nested fields and array elements too. So flexible schemas don't cost you query speed.

// Index a nested field and an array field
db.users.createIndex({ 'address.city': 1 });
// Now queries on city use an index:
db.users.find({ 'address.city': 'Chicago' });

// Multikey index on array field - indexes each element
db.products.createIndex({ tags: 1 });
db.products.find({ tags: 'electronics' }); // uses multikey index

Transactions: Tables vs Collections

Since v4.0, MongoDB supports multi-document transactions. But by embedding related data in one document, you often get atomic updates without needing them at all.

// Single-document atomicity (always available)
// Updating order status and adding a tracking number
db.orders.updateOne(
  { _id: orderId },
  { $set: { status: 'shipped', trackingNumber: 'UPS123456' } }
);
// These two field updates happen atomically - no transaction needed

When to Choose Tables Over Collections

Sometimes SQL tables are the better pick: stable schemas, heavy JOINs, or strict foreign-key integrity. Choose the right tool, not the trendiest one.

Quick Check

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

Lesson Recap

You learned collections don't force a schema, MongoDB embeds related data to skip JOINs, and every collection auto-indexes _id. Next: databases and namespaces.

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

บทเรียน “คอลเลกชันเทียบกับตาราง SQL” ฟรีหรือไม่

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

คุณจะเรียนรู้อะไรในบทเรียน “คอลเลกชันเทียบกับตาราง SQL”

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

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

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

บทเรียน “คอลเลกชันเทียบกับตาราง SQL” ใช้เวลานานแค่ไหน

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

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

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

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

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