我正在查询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;
}
这个怎么样:
if ($cursor->count() > 0) {
$cursor->next();
$image = $cursor->current();
return $image;
} else {
return false;
}
奖金:引自 Doc页面
公共阵列MongoCursor :: current(void)
这将返回NULL直到
MongoCursor :: next()被调用。
这个怎么样:
if ($cursor->count() > 0) {
$cursor->next();
$image = $cursor->current();
return $image;
} else {
return false;
}
奖金:引自 Doc页面
公共阵列MongoCursor :: current(void)
这将返回NULL直到
MongoCursor :: next()被调用。
raina77ow提供的解决方案使用 蒙戈 被标记为遗产的图书馆。
目前只有一种方法可以从游标中获取第一个元素 - 使用 MongoDB的\驱动程序\光标::指定者 方法:
$cursor = $collection->find();
$firstDocument = $cursor->toArray()[0];