简体   繁体   English

如何在 mongo db 中创建父子模式并检索数据

[英]How to make parent child schema in mongo db and retrive the data

need help to design and fetch data from MongoDB, the requirement is needed to create a category schema where each category can have multiple child categories and each child category can have further child category and so on, so if in MySQL I have designed it then I can design it like below需要帮助来设计和从 MongoDB 获取数据,需要创建一个类别模式,其中每个类别可以有多个子类别,每个子类别可以有更多的子类别等等,所以如果在 MySQL 中我已经设计了它,那么我可以像下面这样设计

category table
id name parent_id

So as you can see the parent_id will be the primary key of the category id and so on, no matter how many children comes it can be handle in it, but I am not getting how to do this in mongo schema as I am new in this db and after making the schema how can I fetch the categories with there children and there children.因此,如您所见,parent_id 将是类别 id 的主键,依此类推,无论有多少孩子都可以在其中处理,但是我不知道如何在 mongo 模式中执行此操作,因为我是新手这个数据库以及在制作模式之后如何获取带有孩子和孩子的类别。

There are multiple ways to achieve this but to keep it simple if you want to go with embedding which is best if your category document has limited child and sub-child.有多种方法可以实现这一点,但如果您想使用嵌入,则最好保持简单,如果您的类别文档具有有限的孩子和子孩子。

{
    _id: ObjectId("507f1f77bcf86cd799439011"),
    name: 'adsfa',
    childCategories: [
      {
          _id: ObjectId("507f1f77bcf86cd799439012"),
          name: 'asefda',
          childCategories: [
             {
                _id: ObjectId("507f1f77bcf86cd799439013"),
                name: 'afsd',
             },
          ],
      },
    ],
}

As for querying data you'll simply query for parent document _id which will return the whole document with child and all sub child categories.至于查询数据,您只需查询父文档_id ,它将返回包含子类和所有子子类的整个文档。 Please do note that this schema might not always be good for you if your child and subchild categories are expected to go on to a large number.请注意,如果您的子项和子子项类别数量较多,则此模式可能并不总是适合您。 In this case you can consider reshaping schema to make use of references.在这种情况下,您可以考虑重塑架构以利用引用。 Below is the example for such scenario以下是此类场景的示例

{
    _id: ObjectId("507f1f77bcf86cd799439011"),
    name: 'Parent or child category name',
    parent: ObjectId("507f1f77bcf86cd799439012"),
}

In this case you have to use lookups or populates in case of mongoose to fill the data for your parent.在这种情况下,您必须使用查找或填充以防猫鼬为您的父母填写数据。 But again that totally depends on your use case.但这同样完全取决于您的用例。 So I recommend you read a little about how to structure you document database and pros and cons for each approach.因此,我建议您阅读一些有关如何构建文档数据库以及每种方法的优缺点的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM