Embedding 在一个文档内存储相关数据(嵌套);Referencing 在单独的文档中存储数据,通过 id 链接。这是 MongoDB 中的核心建模决策,在读取性能、数据大小和更新复杂性方面有不同的权衡。
Embedding — 嵌套在文档内
js
{
: (),
: ,
: { : , : },
: [
{ : , : },
{ : , : }
]
}
Embedding 在一个文档内存储相关数据(嵌套);Referencing 在单独的文档中存储数据,通过 id 链接。这是 MongoDB 中的核心建模决策,在读取性能、数据大小和更新复杂性方面有不同的权衡。
{
: (),
: ,
: { : , : },
: [
{ : , : },
{ : , : }
]
}
// posts collection
{ _id: ObjectId("p1"), title: "My Post", authorId: ObjectId("u1") }
// users collection
{ _id: ObjectId("u1"), name: "Ann", email: "[email protected]" }
// comments collection
{ _id: ObjectId("c1"), postId: ObjectId("p1"), user: "Bob", text: "Great!" }
// ✓ author/comments stored ONCE, updated in one place; no document-size issues
// ✓ each entity managed independently
// ✗ need multiple queries or $lookup to combine (slower reads for related data)
Embedding Referencing
Reads ✓ fast (one query) ✗ multiple queries / $lookup
Data duplication ✗ duplicated (update many) ✓ stored once
Document size ✗ grows (16MB limit risk) ✓ no size concern
Updates ✗ update in every copy ✓ update in one place
Atomicity ✓ atomic (single document) ✗ across documents
Best for contains, accessed-together shared, large, independent, many
// embed a SUBSET for fast reads, reference for the full data
{ title: "Post", author: { _id: ObjectId("u1"), name: "Ann" } } // enough for display
// → reference (author._id) for full details when needed; embed name for the common read
理解 embedding 与 referencing 是 MongoDB 数据建模的核心技能,对于设计高效的 MongoDB 应用程序至关重要。
这个决策——在文档内存储相关数据(embedding)还是在单独的链接文档中(referencing)——直接决定了应用程序的读取性能、数据一致性、文档大小和更新复杂性,使其成为最关键的 MongoDB 设计选择。
理解权衡是关键:embedding 提供快速的单查询读取相关数据和原子更新(适合