MongoDB 多对多的关系应该怎样描述?
阿神
阿神 2017-04-24 09:11:26
0
3
657

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

Student:
    Id
    Name

Course:
    Id
    Name

Relation:
    Student_Id
    Course_Id
阿神
阿神

闭关修行中......

reply all(3)
小葫芦

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?

阿神

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

Peter_Zhu

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/.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template