I'm making a query to a MongoDB and I only want the first object. I know I could use findOne
, but I'm still confused where I'm going wrong.
This does not work:
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
This works though:
if ($cursor->count() > 0) {
$image = null;
foreach($cursor as $obj)
$image = $obj;
return $image;
} else {
return false;
}
How about this:
if ($cursor->count() > 0) {
$cursor->next();
$image = $cursor->current();
return $image;
} else {
return false;
}
Bonus: quote from the Doc page
public array MongoCursor::current (void)
This returns NULL until MongoCursor::next() is called.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With