基于$ cursor1的MongoDB PHP $ cursor2

I have a really simple database-setup: one collection/ archive of all available documents, and users that on specific dates relate to a specific document/ archive _id.

student_123 exams (collection):

{
_id: "2015-02-05-1430162122744",
exam_id: "ex-34"
},
{
_id: "2014-12-05-1430162122744",
exam_id: "ex-981"
},
{
_id: "2015-04-08-1430162148984",
exam_id: "ex-34"
},
{
_id: "2015-01-01-1430162148984",
exam_id: "ex-2"
} ...


all exams (collection):

{
_id: "ex-1",
name: "exam1"
} ...
{
_id: "ex-1003",
name: "exam1003"
}

what i'm trying to achieve is to list all exam names by a descending date-sorted (student) exams-log. which means the log must be sorted (not registered chronologically) AND some exams must be listed several times (several attempts).

the easy and really dirty solution is this:

$test = $collection_student123->find();
$test->sort(array('_id' => -1));
foreach ( $test as $id => $value ) {
        $cursor = $collection_exams->findOne(array( '_id' => $value['exam_id'] ));
        echo $cursor['name'];
}

my "sophisticated" attempt fails, though:

$sorted = [];
$test = $collection_student123->find();
$test->sort(array('_id' => 1));
foreach ( $test as $id => $value ) {
        $sorted[] = $value['exam_id'];
}
$cursor = $collection_exams->find(array(
    'id' => array('$in' => $sorted)
));

foreach ( $cursor as $id => $value )
{
    echo $value['name'];
}
  • 1: The result is not sorted as in $sorted
  • 2: The $collection_exams->find function does NOT return identical IDs (eg. 2nd attempt on same exam ID)

Any clever ideas on how to achieve this? Thanks.

EDIT: The reason i'm interested is that after only 10 iterations the "sophisticated" method is 5x faster than the "dirty" one