We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 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");

<?php

// 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();
$modelObj->changeDB($newdb);
$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);
    }