埋め込み:1対少数のリレーションシップ
密接に結び付いたデータにはサブドキュメントを埋め込み、関連情報を同じ場所に置くことで得られる読み取り性能の利点を測定します。
「埋め込み:1対少数のリレーションシップ」はCoddyKit上の無料MongoDB Academyレッスンです。 これはレッスン1/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応の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
よくある質問
「埋め込み:1対少数のリレーションシップ」レッスンは無料ですか?
はい。「埋め込み:1対少数のリレーションシップ」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、MongoDB Academyコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 MongoDB Academyコースには全4レッスンが含まれています。
「埋め込み:1対少数のリレーションシップ」で何を学びますか?
密接に結び付いたデータにはサブドキュメントを埋め込み、関連情報を同じ場所に置くことで得られる読み取り性能の利点を測定します。 ブラウザで直接実行するハンズオンコードでMongoDB Academyを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
MongoDB Academyを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのMongoDB Academyは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン1/4です。
「埋め込み:1対少数のリレーションシップ」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このMongoDB Academyレッスンでコードを書いて実行できますか?
はい。すべてのMongoDB Academyレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- 埋め込み:1対少数のリレーションシップ
- 参照:1対多と多対多
- 無制限配列のアンチパターン
- スキーマ設計の意思決定フレームワーク