Ms01
Ms01

Reputation: 4702

MongoDB returns empty on find() but content on findOne or when using count()

I am using mongoDB for a new project at work and I got into some troubles which I can't find any solutions for. I have a model in my project which contains a method to fetch some data from MongoDB, which works just fine as long as I use findOne() instead of find().

The method:

public function getData($input) {

        $output = $this->_collection->find($input);
        //$output = $this->_collection->findOne($input);
        Zend_Debug::Dump($output);
        return $output;
    }

When running that piece of code I get this from the dump:

object(MongoCursor)#52 (0) {
}

Using findOne() :

array(12) {
  ["_id"] => object(MongoId)#54 (1) {
    ["$id"] => string(24) "4fd85d178efd307080000001"
  }
  ["autoadd"] => string(1) "1"
  ["name"] => string(5) "Sport"
  ["keyword"] => string(8) "cookie29"
  ["antal"] => string(1) "0"
  ["antal_week_date"] => string(10) "1218818007"
  ["version"] => string(1) "1"
  ["active"] => string(1) "1"
  ["antal_week"] => string(1) "0"
  ["customer_id"] => string(1) "2"
  ["id"] => string(2) "29"
  ["insert_date"] => string(10) "2007-11-21"
}

And when using $output = $this->_collection->find($input)->count();:

int(20)

What am I doing wrong? This might be a simple problem, but I can't find any other way to do this stuff. If you wonder what the input is, it's just an associative array:

$data = array('active' => '1');

Please help me fetch all those 20 nice "rows" of data. I'd be grateful.

Thanks for your advice and better wisdom!

Upvotes: 1

Views: 8986

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230336

find() returns cursor, not the array with actual data. You have to iterate the cursor. This is an example from the documentation

$m = new Mongo();
$db = $m->selectDB('test');
$collection = new MongoCollection($db, 'phpmanual');

// search for documents where 5 < x < 20
$rangeQuery = array('x' => array( '$gt' => 5, '$lt' => 20 ));

$cursor = $collection->find($rangeQuery);
foreach ($cursor as $doc) {
    var_dump($doc);
}

Upvotes: 13

Related Questions