Foreign keys in mongo?

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

\"enter

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

5条回答
  •  南笙
    南笙 (楼主)
    2020-12-12 17:39

    We can define the so-called foreign key in MongoDB. However, we need to maintain the data integrity BY OURSELVES. For example,

    student
    { 
      _id: ObjectId(...),
      name: 'Jane',
      courses: ['bio101', 'bio102']   // <= ids of the courses
    }
    
    course
    {
      _id: 'bio101',
      name: 'Biology 101',
      description: 'Introduction to biology'
    }
    

    The courses field contains _ids of courses. It is easy to define a one-to-many relationship. However, if we want to retrieve the course names of student Jane, we need to perform another operation to retrieve the course document via _id.

    If the course bio101 is removed, we need to perform another operation to update the courses field in the student document.

    More: MongoDB Schema Design

    The document-typed nature of MongoDB supports flexible ways to define relationships. To define a one-to-many relationship:

    Embedded document

    1. Suitable for one-to-few.
    2. Advantage: no need to perform additional queries to another document.
    3. Disadvantage: cannot manage the entity of embedded documents individually.

    Example:

    student
    {
      name: 'Kate Monster',
      addresses : [
         { street: '123 Sesame St', city: 'Anytown', cc: 'USA' },
         { street: '123 Avenue Q', city: 'New York', cc: 'USA' }
      ]
    }
    

    Child referencing

    Like the student/course example above.

    Parent referencing

    Suitable for one-to-squillions, such as log messages.

    host
    {
        _id : ObjectID('AAAB'),
        name : 'goofy.example.com',
        ipaddr : '127.66.66.66'
    }
    
    logmsg
    {
        time : ISODate("2014-03-28T09:42:41.382Z"),
        message : 'cpu is on fire!',
        host: ObjectID('AAAB')       // Reference to the Host document
    }
    

    Virtually, a host is the parent of a logmsg. Referencing to the host id saves much space given that the log messages are squillions.

    References:

    1. 6 Rules of Thumb for MongoDB Schema Design: Part 1
    2. 6 Rules of Thumb for MongoDB Schema Design: Part 2
    3. 6 Rules of Thumb for MongoDB Schema Design: Part 3
    4. Model One-to-Many Relationships with Document References

提交回复
热议问题