임베딩: 일대소 관계
밀접하게 결합된 데이터를 하위 문서로 임베딩하고 관련 정보를 함께 배치할 때 얻는 읽기 성능상의 이점을 측정합니다.
임베딩: 일대소 관계은(는) CoddyKit의 무료 MongoDB Academy 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 MongoDB Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. MongoDB Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
What Is Document Embedding?
Embedding means storing related data directly inside a parent document rather than in a separate collection. Instead of linking two collections with a foreign key, you nest the related data as a sub-document or an array of sub-documents. This is MongoDB's most powerful design tool because it allows a single read to retrieve the parent and all its related data at once.
The One-to-Few Relationship
A one-to-few relationship exists when one parent document has a small, bounded number of child items—typically fewer than a few dozen. Classic examples include a blog post and its comments, a user and their addresses, or an order and its line items. When the child count is predictable and small, embedding is almost always the right choice.
Embedding a User's Addresses
Consider a users collection where each user has one or two delivery addresses. Instead of a separate addresses collection, embed them directly. This means finding a user and their addresses requires one query with zero joins.
db.users.insertOne({
name: 'Alice',
email: 'alice@example.com',
addresses: [
{ label: 'home', street: '123 Maple St', city: 'Austin', zip: '78701' },
{ label: 'work', street: '456 Oak Ave', city: 'Austin', zip: '78702' }
]
});Reading Embedded Data in One Query
When data is embedded, you retrieve the parent document and all its children with a single findOne. There is no need for a $lookup or a second round trip to the database. This makes reads faster and the application code simpler, since the entire object graph arrives in one response.
// Retrieve user AND their addresses in a single read
const user = await db.collection('users').findOne(
{ email: 'alice@example.com' },
{ projection: { name: 1, addresses: 1 } }
);
console.log(user.addresses); // Array of embedded address objectsUpdating an Embedded Sub-Document
To update an embedded sub-document, use the positional operator $ or dot notation. For example, changing the zip code of Alice's home address targets the specific array element that matches a filter condition. Embedded updates happen atomically at the document level—no transaction needed.
db.users.updateOne(
{ email: 'alice@example.com', 'addresses.label': 'home' },
{ $set: { 'addresses.$.zip': '78703' } }
);Read Performance Advantage
MongoDB stores documents as contiguous BSON blobs on disk. When you embed related data, the engine reads one block of storage instead of two separate collection scans. This co-location of related data is the core reason embedded documents outperform referencing for read-heavy workloads where the parent and children are almost always accessed together.
Embedding in Mongoose
In Mongoose, you define sub-document schemas and nest them inside the parent schema. Mongoose treats embedded arrays as sub-document arrays, providing full type validation and lifecycle hooks on each element. The parent model saves the entire tree atomically.
const addressSchema = new mongoose.Schema({
label: String,
street: String,
city: String,
zip: String
});
const userSchema = new mongoose.Schema({
name: String,
email: String,
addresses: [addressSchema] // embedded array of sub-documents
});
const User = mongoose.model('User', userSchema);When Embedding Shines
Embedding works best when: (1) the child data is always accessed with the parent; (2) the number of children is small and bounded; (3) the children do not need their own independent lifecycle (e.g., they are never queried or updated in isolation). If all three conditions are true, embedding is almost certainly the optimal choice.
Document Size Limit
Every MongoDB document has a hard size limit of 16 MB. For one-to-few relationships, this is rarely a concern—a user with ten addresses or an order with twenty line items is well within the limit. However, you should monitor document growth over time to make sure embedding does not push documents toward the ceiling.
Embedding vs Referencing at a Glance
Use this quick comparison to guide your choice:
- Embedding: one query, atomic updates, small bounded child count
- Referencing: flexible child count, shared children, independent child queries
For one-to-few relationships, embedding wins on almost every metric. You avoid extra network round trips and keep your schema simple.
Practical Example: Blog Post Tags
A blog post typically has a small, fixed set of tags. Rather than maintaining a separate tags collection with references, embed the tags as an array of strings directly in the post document. Querying posts by tag is efficient with a multikey index on the tags field, and reading a post always returns its tags in the same document.
db.posts.insertOne({
title: 'Getting Started with MongoDB',
body: 'MongoDB is a document database...',
tags: ['mongodb', 'nosql', 'database'],
author: 'Alice',
createdAt: new Date()
});
// Index the tags array for fast tag-based lookups
db.posts.createIndex({ tags: 1 });Quick Check
Test your understanding of MongoDB & NoSQL Databases concepts from this lesson.
Lesson Recap
In this lesson you learned: embedding places related data inside the parent document, one-to-few relationships benefit from embedding because a single read fetches all data, and Mongoose supports sub-document schemas for type-safe embedded arrays. Next up we explore referencing—when to link documents across collections instead of nesting them.
AI 튜터와 함께 JavaScript을(를) 배우세요 — 무료
브라우저에서 실제 코드를 작성하고 실행하며, 24/7 AI 튜터로부터 즉각적인 도움을 받고, 웹이나 앱에서 중단한 부분부터 계속 학습하세요.
- 코스
- 30
- 레슨
- 120
자주 묻는 질문
“임베딩: 일대소 관계” 강의는 무료인가요?
네 — “임베딩: 일대소 관계” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 MongoDB Academy 강의 전체를 잠금 해제할 수 있습니다. MongoDB Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“임베딩: 일대소 관계”에서 뭘 배우나요?
밀접하게 결합된 데이터를 하위 문서로 임베딩하고 관련 정보를 함께 배치할 때 얻는 읽기 성능상의 이점을 측정합니다. 브라우저에서 직접 실행하는 실습 코드로 MongoDB Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
MongoDB Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 MongoDB Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“임베딩: 일대소 관계” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 MongoDB Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 MongoDB Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 임베딩: 일대소 관계
- 참조: 일대다 및 다대다
- 무제한 배열 안티 패턴
- 스키마 설계 결정 프레임워크