Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Only first object from Mongo Cursor

Tags:

php

mongodb

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;
}   
like image 773
xbonez Avatar asked Jun 21 '12 22:06

xbonez


1 Answers

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.

like image 187
raina77ow Avatar answered Oct 23 '22 10:10

raina77ow