我有一个结构为
的教室集合{
"_id" : ObjectId("517a54a69de5ee980b000003"),
"class_name" : "A",
"students" : [{
"sname" : "John",
"age" : "13"
}, {
"sname" : "Marry",
"age" : "12"
}, {
"sname" : "Gora",
"age" : "12"
}]
}
使用php,我喜欢根据class _id获取和列出所有学生。我们怎么做呢?
UPDATE我使用的查询:
$student_list=$collection->find(array(" rid"=>new MongoId($theObjId )),
array(
"students" => 1,
)
);
我想把所有学生的名单打印出来。我不能通过使用Foreach循环来管理它
你所需要做的就是调用findOne()
而不是find()
:
$classroom = $collection->findOne(
array( '_id' => new MongoId($theObjId )),
array( 'students' => 1 )
);
$classroom['students']; // will be an array of students
http://php.net/manual/en/mongocollection.findone.php $student_list是一个包含多行的MongoCursor。你需要循环遍历它来访问你要找的行。像这样:
$cursor = $collection->find(array("_id"=>new MongoId($theObjId)),
array("students" => 1));
foreach($cursor as $row)
foreach($row['students'] as $student)
echo $student["sname"], $student["age"];
同样,考虑使用findOne。