【问题标题】:Manually convert embedded documents to references in MongoDB手动将嵌入文档转换为 MongoDB 中的引用
【发布时间】:2016-02-23 17:05:23
【问题描述】:

假设我有一个包含作者文档的数组字段的书籍文档,我决定规范化数据并创建“作者”集合。如何检索作者详细信息,以及如何将其添加到名为“authors”的新集合中,然后在书籍集合中的数组中引用它?

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    您可以很容易地创建作者集合,每个集合都会生成唯一的 id,当您创建图书收藏时,您必须从其详细信息(如名字)中找到作者 ID,并将其作为 author_id 放置在图书收藏中

    喜欢 ....

     [authors: {
                id:"54385-ab4f5-c356-bf38"
                firstname: "Kristina",
                lastname: "Chodorow",
            }
    
    ]
    

    就像在 node.js 中一样

    domain.author.find{{author.firstname:"Kristina",author.lastname:"Chodorow"},function(err,data){
    console.log(data.id)}}
    

    然后预定

    {
            title: "50 Tips and Tricks for MongoDB Developer",
            published_date: ISODate("2011-05-06"),
            pages: 68,
            language: "English",
            authors_id: 54385-ab4f5-c356-bf38
        }
    

    【讨论】:

      【解决方案2】:

      MongoDB通过嵌入文档与传统的关系数据库完全不同的方法来实现关系,后者封装了它引用的外键特性跨数据库中另一个表的数据。

      根据上述描述作为解决方案,请尝试在 mongodb 中执行以下查询以提取特定作者的详细信息

      db.collection.find({ authors: { $elemMatch: { firstname: "Kristina", lastname:'Chodorow' } } },
         { authors: { $elemMatch: { firstname: "Kristina", lastname:'Chodorow' } } }
      )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-03
        • 2020-04-10
        • 1970-01-01
        • 2012-12-20
        • 2018-08-21
        • 2021-09-19
        相关资源
        最近更新 更多