0

I have a classroom collection structured as

{
  "_id" : ObjectId("517a54a69de5ee980b000003"),
  "class_name" : "A",
  "students" : [{
    "sname" : "John",
    "age" : "13"
  }, {
    "sname" : "Marry",
    "age" : "12"
  }, {
    "sname" : "Gora",
    "age" : "12"
  }]
}

With php, I like to get and list all students based on class _id . How can we do it?

UPDATE The query I use:

$student_list=$collection->find(array(" rid"=>new MongoId($theObjId )), 
        array(
            "students" => 1,
        )
        );

I want to print it out all the list of the students. I could not manage it by using Foreach loop.

4
  • 1
    do a json_encode and you will get an array. then you can loop through key / val Commented Apr 26, 2013 at 11:29
  • You mean you don't know how to query and return students by class_id? Commented Apr 26, 2013 at 11:39
  • @Satya : json_encode do the work. Can we do it without json_encode? Commented Apr 26, 2013 at 11:48
  • @Satya : +1 for json_encode Commented Apr 26, 2013 at 12:34

2 Answers 2

2

All you need to do is call findOne() instead of 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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this also did the job.
1

$student_list is a MongoCursor of multiple rows. You need to loop through that to get access to the row you're looking for. Like so:

$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"];

Also, consider using findOne. It is better suited to your query.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.