2012-06-21 28 views
11

我正在查詢MongoDB,而我只想要第一個對象。我知道我可以使用findOne,但我仍然對我出錯的地方感到困惑。從Mongo光標獲取第一個對象

這不起作用:

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; 
} 

回答

14

如何:

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

獎勵:引自the Doc page

公共數組MongoCursor :: current(void)
這將返回NULL直到 MongoCursor :: next()被調用。

+0

是的,這工作。哇...這對我來說很愚蠢。我會盡快接受。 – xbonez

+0

沒關係,我很驚訝,也不是很久以前。 ) – raina77ow

0

raina77ow提供的解決方案使用Mongo庫標記爲遺留。

目前只有一個辦法從光標獲得第一個元素 - 使用MongoDB\Driver\Cursor::toArray方法:

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

調用未定義的方法MongoCursor :: toArray() – theBugger