Question

I have a xampp 1.7.3 instance running and a MongoDB 1.2.4 server on the same machine.

I want to connect them, so I basically have been following this tutorial on php.net, it seems to connect but the cursors are always empty. I don't know what am I missing.

Here is the code I am trying. The cursor->valid always says false. thanks

<?php
$m = new Mongo(); // connect
try {
  $m->connect();
} catch (MongoConnectionException $ex) {
  echo $ex;
}
echo "conecta...";
$dbs = $m->listDBs();
if ($dbs == NULL) {
  echo $m->lastError();
  return;
}
foreach($dbs as $db) {
  echo $db;
}

$db = $m->selectDB("CDO");
echo "elige bd...";
$col = $db->selectCollection("rep_consulta");
echo "elige col...";

$rangeQuery = array('id' => array( '$gt' => 100));
$col->insert(array('id' => 456745764, 'nombre' => 'cosa'));
$cursor = $col->find()->limit(10);
echo "buscando...";
var_dump($cursor);
var_dump($cursor->valid());
if ($cursor == NULL) echo 'cursor null';
while($cursor->hasNext()) {
    $item = $cursor->current();
    echo "en while...";
    echo $item["nombre"].'...';
}

?>

doing this by command line works perfect

use CDO
db.rep_consulta.find()
-- lot of data here
Was it helpful?

Solution

When iterating the results of the query you are not advancing the cursor. Running your code above is causing an infinite loop since the cursor isn't being advanced. Try changing :

$item = $cursor->current();

to

$item = $cursor->getNext();

Personally, I prefer this syntax :

foreach ($cursor as $item)
{
    var_dump($item);
}

Edit

The following code is working fine for me. Can you try it out?

$m = new Mongo();

$db = $m->CDO;
$col = $db->rep_consulta;

$col->insert(array('id' => 456745764, 'nombre' => 'cosa'));

$cursor = $col->find()->limit(10);

foreach ($cursor as $item)
{
    var_dump($item);
}

Edit++

By the way, $cursor->valid() will not return true until you advance the cursor to the first item of the result. Thats why you are getting false. You have yet to advance the cursor at that point in your code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top