0Pricing
MongoDB Academy · 강의

컬렉션과 SQL 테이블 비교

MongoDB 컬렉션과 관계형 테이블을 비교하고, 유연한 스키마가 데이터 설계를 어떻게 바꾸는지 이해합니다.

컬렉션과 SQL 테이블 비교은(는) CoddyKit의 무료 MongoDB Academy 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 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 테이블 비교” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 MongoDB Academy 강의 전체를 잠금 해제할 수 있습니다. MongoDB Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“컬렉션과 SQL 테이블 비교”에서 뭘 배우나요?

MongoDB 컬렉션과 관계형 테이블을 비교하고, 유연한 스키마가 데이터 설계를 어떻게 바꾸는지 이해합니다. 브라우저에서 직접 실행하는 실습 코드로 MongoDB Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

MongoDB Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 MongoDB Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“컬렉션과 SQL 테이블 비교” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 MongoDB Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 MongoDB Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. BSON 문서란 무엇인가요?
  2. 컬렉션과 SQL 테이블 비교
  3. 데이터베이스, 컬렉션, 네임스페이스
  4. mongosh 셸 핵심
← MongoDB Academy(으)로 돌아가기