buley
buley

Reputation: 29238

Why would findOne($query) work on a collection and find($query) not using PHP's Mongo driver?

I'm using PHP to talk with a Mongo use findOne($query) on a db.collection it returns a result as I would expect. But changing that command to find() returns nothing.

From the shell, if you use db.collection.find() it returns all documents. Can anyone explain why the PHP driver's find() wouldn't return results even when findOne() does while using the exact same query?

UPDATE: Here's the code.

find() (doesn't work):

  $db = $connection->selectDB( $database );
  $returned_collection = $db->selectCollection( $collection );
  $cursor = $returned_collection->find( $query );

);

find() debug output:

query: array(1) {
  ["user_id"]=>
  string(13) "4d03d13b71676"
}
1292099894 > mongo_wrapper.class.php > returned_collection: events.votes 
db: object(MongoDB)#41 (2) {
  ["w"]=>
  int(1)
  ["wtimeout"]=>
  int(10000)
}
cursor: object(MongoCursor)#43 (0) {
}

findOne() (works):

  $db = $connection->selectDB( $database );
  $returned_collection = $db->selectCollection( $collection );
  $cursor = $returned_collection->findOne( $query );

findOne() debug output:

query: array(1) {
  ["user_id"]=>
  string(13) "4d03d13b71676"
}
1292099906 > mongo_wrapper.class.php > returned_collection: events.votes 
db: object(MongoDB)#7862 (2) {
  ["w"]=>
  int(1)
  ["wtimeout"]=>
  int(10000)
}
cursor: array(7) {
  ["_id"]=>
  object(MongoId)#7849 (1) {
    ["$id"]=>
    string(24) "4d03d842d0645afaab4e92f6"
  }
  ["user_id"]=>
  string(13) "4d03d13b71676"
  ["timestamp"]=>
  int(1292095809)
  ["context"]=>
  string(3) "ms3"
  ["uri"]=>
  string(120) "http://feeds.marketwatch.com/~r/marketwatch/podcasts/MarketwatchStupidInvestmentOfTheWeek/~3/3H-tMQLS9AA/siotw103009.mp3"
  ["type"]=>
  string(8) "category"
  ["vote"]=>
  int(-1)
}

Both use this debug code:

    if($debug->enabled) {
        echo time() . " > mongo_wrapper.class.php > returned_collection: $returned_collection \n";
        if($debug->dump) {
            echo "db: ";
            var_dump( $db );
            echo "cursor: ";
            var_dump( $cursor );
        }
    }

Upvotes: 4

Views: 3021

Answers (1)

thirtydot
thirtydot

Reputation: 228182

<?php

$connection = new Mongo();

$db = $connection->database;

$collection = $db->collection;

echo '<pre>';

print_r($collection->findOne());

$cursor = $collection->find();
foreach ($cursor as $id => $value) {
    echo "$id: ";
    print_r($value);
}

echo '</pre>';

?>

Upvotes: 3

Related Questions