从Mongo Cursor获取第一个对象

xbo*_*nez 12 php mongodb

我正在查询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
Run Code Online (Sandbox Code Playgroud)

这有效:

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

rai*_*7ow 15

这个怎么样:

if ($cursor->count() > 0) {
    $cursor->next();
    $image = $cursor->current();
    return $image;
} else {
    return false;
}
Run Code Online (Sandbox Code Playgroud)

奖励:来自Doc页面的引用

public array MongoCursor :: current(void
)在调用MongoCursor :: next()之前返回NULL.