douliang2935 2015-04-27 20:08
浏览 75

基于$ 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

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
    • ¥15 有了解d3和topogram.js库的吗?有偿请教
    • ¥100 任意维数的K均值聚类
    • ¥15 stamps做sbas-insar,时序沉降图怎么画
    • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
    • ¥15 关于#Java#的问题,如何解决?
    • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
    • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
    • ¥15 cmd cl 0x000007b
    • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line