I have a simple record that should return based on a query. As soon as I try to get the results I get the following error:
Cursors cannot yield multiple iterators
The code I have is very simple:
$db = \core\databaseUtilities\getDbConnection();
$filter = [ 'email' => $email ];
$query = new \MongoDB\Driver\Query($filter);
$res = $db->executeQuery($db->dbName.".users", $query);
$records = $res->toArray();
It fails on the last line.
I found some code examples on the web on how to query on they all pretty much looked the same. Here is the reference I used: http://php.net/manual/en/class.mongodb-driver-cursor.php
I found the issue and it had nothing to do with the code. I am posting the answer as other may come across the same issue. It had to do with my IDE Visual Studio code. However, I assume this may not be restricted to my IDE. The problem was I had a watch on $res->toArray(); so by the time the code go to the last line in my example it was trying to iterate again. As soon as I removed the watch my issues went away no code changes necessary.
You can use PHP's iterator_to_array function, as suggested in example of the MongoCursor docs:
$res = $db->executeQuery($db->dbName.".users", $query);
$records = iterator_to_array($res);