search

Home  >  Q&A  >  body text

MongoDB 多对多的关系应该怎样描述?

比如下面这种学生选课的模型,既要知道学生选了哪些课,又要知道课被哪些学生选了。传统的 SQL 就是下面这写法了,如果换成 key-value 的,该怎么描述呢?

Student:
    Id
    Name

Course:
    Id
    Name

Relation:
    Student_Id
    Course_Id
阿神阿神2762 days ago659

reply all(3)I'll reply

  • 高洛峰

    高洛峰2017-04-24 09:13:26

    It can be designed like this. Each document in the collection stores a student's course selection data:

    // students
    {
        _id: ObjectId('4e7020cb7cac81af7136236b'),
        name: "...",
        choose_lesson: [
            {_id:ObjectId('4e7020cb7cac81af71362361'),
             lesson_name: "..."
            },
            {_id:ObjectId('4e7020cb7cac81af71362362'),
             lesson_name: "..."
            }
        ]
    }
    

    What courses did the students choose?

    db.students.find(
        {_id: ObjectId('4e7020cb7cac81af7136236b')},
        {choose_lesson: 1}
    )
    

    What student options are there for a course?

    db.students.find(
        {choose_lesson: {$elemMatch: {lesson_name: "..."}}},
        {name: 1}
    )
    

    With reference to mongodb, how to design the user like function more reasonably?

    reply
    0
  • 阿神

    阿神2017-04-24 09:13:26

    In this business, I think it’s the same.

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-24 09:13:26

    Save Student's Id and Course's Id directly in Relation, or use DBRefs. Personally, I think the former is fine. Please refer to: http://docs.mongodb.org/manual/reference/database-references/.

    reply
    0
  • Cancelreply