I am trying to run the following code in PHP to query a MongoDB:
<?
$m = new Mongo(); // connect
$dogs = $m->dogs;
$races = $dogs->newdogs;
$js = "function() {
return this.location == 'SHEFFIELD'
}";
$dataSet = $races->find(array('$where' => $js));
foreach ($dataSet as $r){
}
?>
When I run this and watch the console, I see the query being run once.
When I change the foreach loop to be nested within another one like this:
foreach(range(1,5) as $test){
foreach ($dataSet as $r){
}
}
I see the query being run 7 times in the console?
Is this something stupid I am doing? A scoping issue? Or am I just misunderstanding how MongoDB is supposed to work?
Thanks
AH
This happens because
$dataSetis aMongoCursor, not an array. AMongoCursoris a representation of a query. It will be turned into an array “on-demand”, that means that when you useforeachon it,$dataSetis converted into an array by simply querying.Since you do it within another loop, the
MongoCursoris executed every time it encounters theforeach. If you don’t want that behaviour, you can useiterator_to_array, since aMongoCursoris just an iterator:EDIT: Keep in mind that
iterator_to_arrayconverts the entire result set into an array in memory. If you have a very big result set, this can cause huge and unnecessary memory consumption. It’s advisable to stick with a singleforeachcall, since it will only load one single row into memory at once.