Symfony2 's mongoDB returns a loggablecursor i

2020-07-18 10:42发布

问题:

I currently use the DoctrineMongoDbBundle to make requests the my mongodb database.

Here's the call in 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 didnt work.

The echos printed:

Array ( [prop] => 1 ) 
101
Doctrine\ODM\MongoDB\LoggableCursor0

It means that the query is correct but the count should be "2" and the type should be an Animal array.

Why is the reposity returning a LoggableCursor0 instead of an Animal array?

[edit] How could it return an Animal array?

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

回答1:

Use 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 array of entities, use array_values() function. Like this:

$entities = array_values($entities);


回答2:

findBy returns a Cursor in MongoDB ODM unlike doctrine orm.

Try:

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


回答3:

If you want a bit more flexibility when storing entities 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)
}