Foreign keys in mongo?

前端 未结 5 1128
渐次进展
渐次进展 2020-12-12 17:16

\"enter

How do I design a scheme such this in MongoDB? I think there are no foreign ke

5条回答
  •  旧时难觅i
    2020-12-12 17:37

    How to design table like this in mongodb?

    First, to clarify some naming conventions. MongoDB uses collections instead of tables.

    I think there are no foreign keys!

    Take the following model:

    student
    { 
      _id: ObjectId(...),
      name: 'Jane',
      courses: [
        { course: 'bio101', mark: 85 },
        { course: 'chem101', mark: 89 }
      ]
    }
    
    course
    {
      _id: 'bio101',
      name: 'Biology 101',
      description: 'Introduction to biology'
    }
    

    Clearly Jane's course list points to some specific courses. The database does not apply any constraints to the system (i.e.: foreign key constraints), so there are no "cascading deletes" or "cascading updates". However, the database does contain the correct information.

    In addition, MongoDB has a DBRef standard that helps standardize the creation of these references. In fact, if you take a look at that link, it has a similar example.

    How can I solve this task?

    To be clear, MongoDB is not relational. There is no standard "normal form". You should model your database appropriate to the data you store and the queries you intend to run.

提交回复
热议问题