0Pricing
MongoDB Academy · 강의

스키마 설계 결정 프레임워크

쿼리 패턴, 쓰기 빈도, 문서 증가를 확인하는 체계적인 목록을 적용하여 어떤 도메인에서든 임베딩과 참조 중 적합한 방식을 선택합니다.

스키마 설계 결정 프레임워크은(는) CoddyKit의 무료 MongoDB Academy 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 MongoDB Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. MongoDB Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Why a Decision Framework Matters

MongoDB's schema flexibility is powerful but can lead to analysis paralysis. Should you embed or reference? When is the choice not obvious? A structured decision framework replaces guesswork with a repeatable checklist. By asking the same questions about query patterns, write frequency, and document growth, you can arrive at the right schema for any domain—consistently.

Step 1: Identify Query Patterns

Start by listing the most frequent read queries your application makes. Ask: do these queries always need the parent and children together, or are children queried independently? If child data is almost always fetched with its parent, embedding eliminates a round trip. If children are frequently queried, sorted, or filtered on their own, referencing keeps queries simple and indexes focused.

Step 2: Estimate Data Size and Growth

For every potential array or nested structure, ask: how many elements will this have at steady state, and can it grow without bound? Use rough business rules: a user rarely has more than 5 addresses (embed), but can write thousands of reviews (reference). Anything with an unbounded or unknown upper limit is a candidate for a separate collection.

Step 3: Evaluate Write Frequency

Consider how often the child data is written compared to the parent. Embedding means every child update rewrites the parent document, triggering a storage move if the document grows. If children are updated very frequently and independently of the parent, the overhead of rewriting the parent each time favours referencing—child documents update in place without touching the parent at all.

Step 4: Check for Data Sharing

Ask whether the child data is owned by one parent or shared across multiple parents. An address is owned by a single user—safe to embed. A product in a catalogue is referenced by potentially thousands of orders—it must be in its own collection to avoid duplication and stale data. Shared data should always be referenced, never embedded.

Step 5: Assess Atomicity Requirements

MongoDB guarantees atomic writes at the document level for free—no transactions needed. If you need to update a parent and its children atomically, embedding keeps both in the same document so any update is atomic by default. If you reference across two collections and need atomicity, you must use a multi-document transaction, which adds latency and complexity.

The Framework Decision Table

Apply these rules in order:

  • Children always fetched with parent + small count + owned by parent: EMBED
  • Children queried independently or shared: REFERENCE
  • Children can grow without bound: REFERENCE (or bucket pattern)
  • Atomic update required across parent + children: EMBED (or transaction)
  • Write frequency of children high relative to parent: REFERENCE

If multiple rules conflict, referencing is the safer default.

Example: E-Commerce Order Schema

Apply the framework to an order in an e-commerce system. Line items: always fetched with order, small count (under 50), owned by order → embed. Shipping address: snapshot at order time, never shared → embed. Customer: shared across thousands of orders → reference. Product catalogue: shared across orders, updated independently → reference.

db.orders.insertOne({
  _id: ObjectId(),
  customerId: ObjectId('c1'),        // reference — shared data
  shippingAddress: {                 // embed — point-in-time snapshot
    street: '123 Maple St',
    city: 'Austin'
  },
  items: [                           // embed — small, owned by order
    { productId: ObjectId('p1'), qty: 2, price: 19.99, name: 'Widget' }
  ]
});

Example: Social Media Schema

Apply the framework to a social media post. Post author: shared across posts → reference. Post body and metadata: owned by post, small → embed. Likes (count only): numeric field → embed as a counter. Comments: potentially thousands, queried and paginated independently → reference in a separate comments collection.

db.posts.insertOne({
  _id: ObjectId(),
  authorId: ObjectId('u1'),           // reference
  title: 'Why MongoDB rocks',
  body: '<p>Because documents...</p>',
  tags: ['mongodb', 'nosql'],         // embed — small, owned
  likesCount: 0,                      // embed — simple counter
  createdAt: new Date()
  // comments live in db.comments, NOT embedded here
});

Evolving Your Schema Over Time

The right schema at launch may not be the right schema at scale. Start with the simplest correct design. If you later discover that an embedded array is growing too large, migrate it to a separate collection. MongoDB's flexible schema makes incremental evolution possible—you can write new documents in the new shape while keeping old ones, then backfill with a migration script.

Documenting Your Schema Decisions

Write down the reasoning behind each schema choice while it is fresh. A comment in a Mongoose schema file or a short design document explaining why items are embedded but customerId is referenced pays enormous dividends when a new engineer joins or when you revisit the schema six months later. Schema design is a deliberate act, not an accident.

const orderSchema = new mongoose.Schema({
  customerId: { type: mongoose.Schema.Types.ObjectId, ref: 'Customer' }, // reference: shared
  shippingAddress: addressSchema,  // embed: point-in-time snapshot
  items: [lineItemSchema],         // embed: small, always with order
  status: { type: String, enum: ['pending', 'shipped', 'delivered'] },
  createdAt: { type: Date, default: Date.now }
});

Quick Check

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

Lesson Recap

In this lesson you learned: the five-step decision framework covers query patterns, data size, write frequency, sharing, and atomicity, shared data always belongs in a separate referenced collection, and schema decisions should be documented alongside the code. Next up we explore schema validation with JSON Schema to enforce data quality in MongoDB collections.

자주 묻는 질문

“스키마 설계 결정 프레임워크” 강의는 무료인가요?

네 — “스키마 설계 결정 프레임워크” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 MongoDB Academy 강의 전체를 잠금 해제할 수 있습니다. MongoDB Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“스키마 설계 결정 프레임워크”에서 뭘 배우나요?

쿼리 패턴, 쓰기 빈도, 문서 증가를 확인하는 체계적인 목록을 적용하여 어떤 도메인에서든 임베딩과 참조 중 적합한 방식을 선택합니다. 브라우저에서 직접 실행하는 실습 코드로 MongoDB Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

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

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

“스키마 설계 결정 프레임워크” 강의는 얼마나 걸리나요?

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

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

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

이 강의의 모든 강의

  1. 임베딩: 일대소 관계
  2. 참조: 일대다 및 다대다
  3. 무제한 배열 안티 패턴
  4. 스키마 설계 결정 프레임워크
← MongoDB Academy(으)로 돌아가기