简体   繁体   English

如何在不使用中间表的情况下在MongoDB中建模多对多关系?

[英]How do you model many-to-many relationships in MongoDB without using an intermediate table?

I'm trying to model a many-to-many relationship in MongoDB with the added requirement that I keep track of "meta-data" on the relationship. 我正在尝试在MongoDB中建立多对多关系的模型,并增加了对关系进行“元数据”跟踪的要求。

The models by themselves would look simple like this: 这些模型本身看起来很简单,如下所示:

Student model
{ 
  _id: <ObjectID1>,
  name: "Foo Bar"
}

School model
{ _id: <ObjectID123>,
  name: "Cityville Highschool",
  location: "Cityville, Stateville"
}

Now, I want to link these in a many-to-many relationship so Students can be part of multiple Schools, and Schools can have many Students. 现在,我想将这些链接成多对多关系,以便学生可以成为多个学校的一部分,并且学校可以有许多学生。 Normally in MongoDB you could just keep an array of the other model in each model. 通常在MongoDB中,您可以在每个模型中保留一个其他模型的数组。 For example: 例如:

Student model
{ 
  _id: <ObjectID1>,
  name: "Foo Bar",
  schools: [<SchoolID1>, <SchoolID2>, ...]
}

School model
{ _id: <ObjectID123>,
  name: "Cityville Highschool",
  location: "Cityville, Stateville",
  students: [<StudentID1>, <StudentID2>, ...]
}

But what if I now want to have data on that relationship? 但是,如果我现在想获得有关该关系的数据怎么办? For example, a date on when the student entered and exited the school: "enter_date" and "exit_date". 例如,学生进入和离开学校的日期:“ enter_date”和“ exit_date”。 Normally, in sql, you would have a JOIN table for StudentSchool that looks like this: 通常,在sql中,您将为StudentSchool创建一个JOIN表,如下所示:

StudentSchool:
{ studentId: 123,
  schoolId:  456,
  enter_date: 12-12-2014,
  exit_date:  12-12-2015
}

How would you do this in MongoDB? 您将如何在MongoDB中做到这一点? Some of the options I've ruled out already: 我已经排除的一些选项:

  1. Creating a new Collection (ie StudentSchool collection) that basically imitates the sql JOIN table. 创建一个基本上模仿sql JOIN表的新Collection(即StudentSchool集合)。 Ruled out because doesn't seem the right way to use Mongo, could also be difficult to manage for updates/deletes. 由于似乎不是使用Mongo的正确方法而被排除在外,也可能难以管理更新/删除。

How about, in the Student model, you don't just put SchoolIds into the array, but entire documents providing the meta-data? 在学生模型中,您不只是将SchoolIds放入数组中,而是将整个文档提供元数据? Eg enter_date, exit_date? 例如enter_date,exit_date? Might be too much to have that annotation in both places (ie Student and School), but even that might be practicable, depending on the intended usage. 可能在两个地方(即学生学校)都没有该注释,可能太多了,但是根据预期的用途,即使是这样也是可行的。

Student model
{ 
  _id: <ObjectID1>,
  name: "Foo Bar",
  schools: [
    { _id: <SchoolID1>,
      enter_date: ...,
      exit_date: ...
    },
    { _id: <SchoolID2>,
      enter_date: ...,
      exit_date: ...
    },
    ...
  ]
}

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

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