[英]How to retrieve subdocuments references in MongoDB
Data structure 数据结构
"classrooms" : [
{
id : ObjectId("class1")
"students" : [
ObjectId("student1")
],
},
{
id : ObjectId("class2")
"students" : [
]
}
],
"students" : [
{
"id" : ObjectId("student1"),
"firstname" : "Ciljan",
"age" : NumberInt(23)
},
{
"id" : ObjectId("student2"),
"firstname" : "John",
"age" : NumberInt(19)
}
]
The need 需要
I have to provide a document where there are classrooms and students. 我必须提供一个有教室和学生的文件。 Students could be assigned to a specific classroom, but not always, so a student could keep free. 学生可以被分配到特定的教室,但并不总是,所以学生可以保持自由。 With the previous data structure, I have the subdocument " students " that provides the list of all the available students both assigned and not assigned. 使用以前的数据结构,我有子文档“ 学生 ”,它提供了已分配和未分配的所有可用学生的列表。 I can assign a student to a classroom storing the student id in the classrooms students array. 我可以将学生分配到教室中存储学生ID的教室。
Problem 问题
How can I retrieve these data in order to have for each classroom all the records about their assigned students? 如何检索这些数据,以便为每个教室提供有关其指定学生的所有记录?
Do you mean something like Classroom.find({}).populate('students')
? 你的意思是像Classroom.find({}).populate('students')
? That'll return an array of Classrooms with the student fields populated. 这将返回一系列带有学生字段的教室。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.