MongoDB 通过 embedding 或 referencing 来建模关系(one-to-one、one-to-many、many-to-many)——选择取决于关系的 cardinality、数据的访问方式以及是否共享。与 SQL 的统一 foreign-key 方法不同,MongoDB 为每个关系提供灵活性。
One-to-one
{ : (), : , : { : , : } }
MongoDB 通过 embedding 或 referencing 来建模关系(one-to-one、one-to-many、many-to-many)——选择取决于关系的 cardinality、数据的访问方式以及是否共享。与 SQL 的统一 foreign-key 方法不同,MongoDB 为每个关系提供灵活性。
{ : (), : , : { : , : } }
// ONE-TO-FEW → embed (bounded, accessed together)
{ _id: ObjectId("..."), name: "Ann", addresses: [ {...}, {...} ] } // a few addresses
// ONE-TO-MANY → reference (the "many" side references the "one")
// authors collection: { _id: "a1", name: "Ann" }
// books collection: { _id: "b1", authorId: "a1", title: "..." } // each book references its author
// ONE-TO-SQUILLIONS (huge/unbounded) → ALWAYS reference (never embed unbounded data)
// e.g. a user with millions of log entries → separate collection, reference by userId
关键细节:one-to-few(embed)、one-to-many(从 many 一侧引用)、one-to-squillions(始终引用——永远不要嵌入无界数据,因为 16MB 文档限制和性能原因)。
// reference with an array of ids (on one or both sides)
{ _id: "s1", name: "Student", courseIds: ["c1", "c2"] } // student → courses
{ _id: "c1", name: "Course", studentIds: ["s1", "s2"] } // course → students (optional)
// → query and $lookup to resolve; or a separate "enrollments" collection (junction-like)
Many-to-many 使用引用 id 的数组(在一侧或两侧),或使用类似联接的单独集合来处理富关系数据。
// join referenced data when needed
db.books.aggregate([
{ $lookup: { from: "authors", localField: "authorId", foreignField: "_id", as: "author" } }
]);
建模关系是数据库设计的基础,MongoDB 的灵活的、基于访问模式的方法不同于 SQL 的统一 foreign keys,因此理解如何在 MongoDB 中建模关系对于设计有效的 schema 至关重要。
关键洞察是 MongoDB 通过基于关系特征的 embedding 或 referencing 来建模关系——而理解 cardinality 如何影响选择 是关键技能:one-to-one(通常 embed——一起访问)、one-to-many 及其重要细节(one-to-few → 为有界的一起访问的数据 embed;one-to-many → 从 many 一侧引用;one-to-squillions → 始终引用,永不嵌入无界数据,因为 16MB 文档限制和性能)以及 many-to-many(引用 id 数组,或类似联接的集合)。
this cardinality-driven decision-making(特别是识别何时数据太大/无界而无法嵌入)对于避免常见错误至关重要,例如嵌入无界数组(膨胀文档、触发限制)或过度引用应该嵌入的数据。
理解如何在需要 join 时用 $lookup 解析引用 完成了这个框架。
由于大多数数据模型中实体之间的关系是内在的,而且 MongoDB 的灵活的 per-relationship 方法(基于 cardinality 和访问模式的 embed 或 reference)从根本上不同于且比 SQL 的统一 foreign keys 更细致,理解如何在 MongoDB 中建模关系——基于 cardinality 的 embed/reference 决策(尤其是 one-to-few/many/squillions 的区分)和解析引用——是有效 MongoDB schema 设计的必要的、常用的知识,基于 embed/reference 基础处理每个真实应用程序都有的关系,以及区分健全的 MongoDB 建模与幼稚的关系型迁移的关键领域。
一个包含详细解答的 IT 面试题库——从初级到高级。
捐赠