Michael
Michael

Reputation: 345

How do I check if MongoDB result is empty in PHP

$cursor = $collection->find(/*...*/);

if (empty($cursor)) {
    echo "List is empty!";
} else {
    foreach ($cursor as $products) {
        // do something
    }
}

Unfortunately, empty doesn't work on MongoDB results.

Upvotes: 0

Views: 1426

Answers (3)

AbraCadaver
AbraCadaver

Reputation: 78984

I don't use MongoDB so I have updated based on the comment. Use $collection->count().

Check if it evaluates to a falsey value:

if(!$collection->count()) {

Or check for 0:

if($collection->count() == 0) {

Or you could check empty:

if(empty($collection->count())) {

Upvotes: 1

Michael
Michael

Reputation: 345

we can use the isDead() method of the cursor

if (!$products->isDead()) {
    // there are some results
}

See the relevant documentation on the PHP driver docs

Upvotes: 3

Alaa Morad
Alaa Morad

Reputation: 455

$cursor is an object so it will always evaluate to true

and there is no $cursor->count() in PHP driver for mongodb

Note that PHP driver for Mongodb is different from other drivers.

Try this:

if ($collection->count(...)) {
   // note you must pass the query to the count function
   $cursor = $collection->find(...);
   foreach ($cursor as $products) {

   }
} else {
    echo "List is empty!";
}

OR:

$cursor = $collection->find(...);

if (!count($cursor->toarray())) { // convert to array and count it 

    echo "List is empty!";
} else {

    foreach ($cursor as $products) {
    }
}

Upvotes: 0

Related Questions