We are moving our forum in GitHub Discussions. For questions about Phalcon v3/v4 you can visit here and for Phalcon v5 here.

MongoDB, Using multiple Databases

I see this reference to connect Mongo to use in models, which works great if I define the DB = return $mongo->selectDB("store");


// Simple database connection to localhost
$di->set('mongo', function() {
    $mongo = new MongoClient();
    return $mongo->selectDB("store");
}, true);

// Connecting to a domain socket, falling back to localhost connection
$di->set('mongo', function() {
    $mongo = new MongoClient("mongodb:///tmp/mongodb-27017.sock,localhost:27017");
    return $mongo->selectDB("store");
}, true);

HOWEVER, depending on controller and various other factors during my app process, I actually select different databases. how do I change the selected database later in the app pipleline?

Instead of defining this one in my Services.php file, I want the controller to define what I am looking at.

Is this the most efficient way? (it works...)

In My Controller:

$modelObj = new Model();
$robots = modelObj::find(array(
    array("name" => "TEST")

In My Model:

public function changeDB($db){
       $this->getDI()->set('mongo', function() use ( $db) {
            $mongo = new MongoClient();
            return  $mongo->selectDb($db);
        }, true);