1
votes

I am using mongoDB PHP, when I use find query or aggregation framework, the Result is a cursor, I can iterate over the cursor using foreach loop or while loop. For example I have the following query to execute

$result = $collection->find();

I am able to iterate over the result using following two methods

1- foreach($result as $mongoid => $doc) {
        echo "mongoid is " . $mongoid;
        print_r($doc);
    }

2- while ( $result->hasNext() ) {
       $doc = $result->getNext();  
       $result->next();  
       print_r( $doc );
       echo "find one doc in cursor\n";

   }

Which of the above iteration method is best and why?

1

1 Answers

0
votes

There's no any significant difference when you use foreach or while in this case. Read loop performance is the same. Using foreach makes your code a bit more readable. You may check write/read loops performance on The PHP Benchmark.