我有一个教室的集合结构如下
{
"_id" : ObjectId("517a54a69de5ee980b000003"),
"class_name" : "A",
"students" : [{
"sname" : "John",
"age" : "13"
}, {
"sname" : "Marry",
"age" : "12"
}, {
"sname" : "Gora",
"age" : "12"
}]
}
使用php,我喜欢根据_id类获取并列出所有学生。我们怎么做呢?
UPDATE我使用的查询:
$student_list=$collection->find(array(" rid"=>new MongoId($theObjId )),
array(
"students" => 1,
)
);
我想把所有学生的名单都打印出来。我无法使用Foreach循环来管理它。
发布于 2013-04-26 12:13:55
$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。它更适合您的查询。
发布于 2013-04-26 11:57:05
您需要做的就是调用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
https://stackoverflow.com/questions/16235257
复制相似问题