4
votes

In the doctrine for relational databases we have the QueryBuilder, can manually write DQL queries and if we really must, can use Doctrine's connection to execute raw SQL. I have not found (nor in the API, nor the documentation) a way to do this in doctrine's mongo project.

How can I execute a native query using mongo odm? (Apart from injecting the doctrine_mongodb.odm.default_connection, or is that really the only way?)

2
Hi!! I'm currently in the same situation, have you managed to solve this problem?rdiaz82
No, I have gone with the approach that I mentioned in my second paragraph: Injecting the connection via the container.Quant

2 Answers

2
votes

Inside your document repository, you can add a private method like this:

private function _getNativeConnection(){
    $connection = $this->getDocumentManager()->getConnection();
    $mongo = $connection->getMongo();
    if(!$mongo){
        $connection->connect();
        $mongo = $connection->getMongo();
    }

    //You can use this as literal strings, or pass them as parameters to the method
    $db = $mongo->selectDB('YOUR_MONGO_DB')->selectCollection("MONGO_COLLECTION");

    return $db;
}

Then, you can use it from another repository method like this:

public function another_public_method{
    ...
    $collection = $this->_getNativeConnection();
    ...
}

The $collection, represents a PHP MongoCollection (http://php.net/manual/en/class.mongocollection.php), with that you can use native Mongo queries (through the class interface). You can't exactly write the literal query, but, through the interface you can do whatever you want, query, aggregate, etc...

This is what you need to do?

Regards

0
votes

You can use this code to access the collection for native queries

$collection = $documentManager->getDocumentCollection('Vendor\MyDocument');

Then you can do things like

$collection->aggregate($pipeline);