MongoDB Academy · 课时

嵌入:一对少关系

您将为紧密耦合的数据嵌入子文档,并衡量将相关信息放在一起所带来的读取性能优势。

第 1 / 4 课13 个步骤

嵌入:一对少关系 是 CoddyKit 上的免费 MongoDB Academy 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 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 objects

Updating 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 — 免费

在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。

课程
30
课程
120

常见问题解答

「嵌入:一对少关系」课时是免费的吗?

是的 — 「嵌入:一对少关系」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 MongoDB Academy 课程的其余内容,请升级到 CoddyKit PRO。 MongoDB Academy 课程共包含 4 节课。

「嵌入:一对少关系」这节课中我会学到什么?

您将为紧密耦合的数据嵌入子文档,并衡量将相关信息放在一起所带来的读取性能优势。 你通过在浏览器中直接运行的动手代码来练习 MongoDB Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 MongoDB Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 MongoDB Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。

「嵌入:一对少关系」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 MongoDB Academy 课中编写并运行代码吗?

能。每节 MongoDB Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 嵌入:一对少关系
  2. 引用:一对多与多对多
  3. 无界数组反模式
  4. 模式设计决策框架
← 返回 MongoDB Academy