Symfony2 mongoDB returns loggablecursor instead of my objects

I am currently using DoctrineMongoDbBundle to query my mongodb database.

Here's the call to my controller:

    $dm = $this->get('doctrine.odm.mongodb.document_manager');
    $entities = $dm->getRepository('MyBundle:Animal')->findBy(array("prop" => "1")); 

    echo print_r($entities->getQuery());
    echo printf(count($entities));
    echo get_class($entities);


Then I tried to serialize $ enitities to json and send it to the client, but it didn't work.

Printed echoes:

Array ( [prop] => 1 ) 


This means that the request is correct, but the count must be "2" and the type must be an array Animal.

Why does the repository return LoggableCursor0 instead of the Animal array?

[edit] How could he return the Animal array?

[edit] What would be the best way to return my result in JSON?


source to share

3 answers

Use the method toArray()

. Like this:

$dm = $this->get('doctrine.odm.mongodb.document_manager');
$entities = $dm->getRepository('MyBundle:Animal')->findBy(array("prop" => "1"))->toArray(); 


If you need to get an array of objects, use the function array_values()

. Like this:

$entities = array_values($entities);




findBy returns cursor in ODM MongoDB as opposed to orm doctrine.


echo printf($entities->count());




If you want a little more flexibility when storing objects as an array, you can do this

$dm = $this->get('doctrine.odm.mongodb.document_manager');
$animalLoggableCursors = $dm->getRepository('MyBundle:Animal')->findBy(array("prop" => "1"));

$animals = array()
while ($animal = $animalLoggableCursors->getNext()) {
    if ($animal->getSomeProperty() == $someValue)
        array_push($animals, $animal)




All Articles