问题 从Mongo Cursor获取第一个对象


我正在查询MongoDB,我只想要第一个对象。我知道我可以用 findOne,但在我出错的地方,我仍然感到困惑。

这不起作用:

if ($cursor->count() > 0) {
    $image = $cursor->current();
    // neither does this work
    // $image = $cursor[0]; 
    return $image;
} else {
    return false;
}   

//echo $image->filename;
// Throws error: Trying to access property of non-object image

这有效:

if ($cursor->count() > 0) {
    $image = null;
    foreach($cursor as $obj)
        $image = $obj;
    return $image;
} else {
    return false;
}   

13004
2018-06-21 22:57


起源



答案:


这个怎么样:

if ($cursor->count() > 0) {
    $cursor->next();
    $image = $cursor->current();
    return $image;
} else {
    return false;
}

奖金:引自 Doc页面

公共阵列MongoCursor :: current(void)
这将返回NULL直到   MongoCursor :: next()被调用。


14
2018-06-21 23:01



是的,这很有效。哇......这对我来说很愚蠢。我会尽快接受。 - xbonez
没关系,不久前我对此感到惊讶。 ) - raina77ow


答案:


这个怎么样:

if ($cursor->count() > 0) {
    $cursor->next();
    $image = $cursor->current();
    return $image;
} else {
    return false;
}

奖金:引自 Doc页面

公共阵列MongoCursor :: current(void)
这将返回NULL直到   MongoCursor :: next()被调用。


14
2018-06-21 23:01



是的,这很有效。哇......这对我来说很愚蠢。我会尽快接受。 - xbonez
没关系,不久前我对此感到惊讶。 ) - raina77ow


raina77ow提供的解决方案使用 蒙戈 被标记为遗产的图书馆。

目前只有一种方法可以从游标中获取第一个元素 - 使用 MongoDB的\驱动程序\光标::指定者 方法:

$cursor = $collection->find();
$firstDocument = $cursor->toArray()[0];

0
2018-06-07 08:39



调用未定义的方法MongoCursor :: toArray() - theBugger