Not able to select the database
and collection dynamically. Read all the solutions but not working for me. selectDB
function not working. It's working only with the static data.
I want to select the database from the configuration file and also select the collections dynamically.
$username='abcd';
$password='efgh';
$m = new MongoDB\Client("mongodb://abcd@127.0.0.1:28015/ijkl", array("username" => $username, "password" => $password));
$db = $m->ijkl;
but I want to have it like
$username='abcd';
$password='efgh';
$m = new MongoDB\Client("mongodb://abcd@127.0.0.1:28015/ijkl", array("username" => $username, "password" => $password));
$l1="ijkl";
$db = $m->$l1;
Expecting to work with dynamic database selection.
Finally it's working
$m = new MongoDB\Client("mongodb://".$mongo_username."@".$mongo_ip.":".$mongo_port."/".$mongo_db, array("username" => $mongo_username, "password" => $mongo_password));
if(!empty($db = $m->$mongo_db))
{
$collection = "test";
if(!empty($collection = $db->$collection))
{
$cursor =$collection->find(array("status"=>0), ['limit' => 10,'skip'=>10]);
foreach ($cursor as $document) {
echo "<b>ID is:</b>";
echo $id=$document["_id"];
echo "<br>";
echo "<b>Link is:</b>";
echo $link=$document["Link"];
echo "<br>";
echo "<b>Status is:</b>";
echo $status=$document["status"];
echo "<br>";
echo "<b>Label is:</b>";
echo $label=$document["Label"];
echo "<br>";
}
}
else
{
echo "Not able to select the collection!";
}
}
else
{
echo "Not able to select the database!";
}
Use mongodb client repo from packagist. You can install it via composer
$ composer require mongodb/mongodb
in your root directory, create file for example app.php
<?php
require 'vendor/autoload.php';
$databases = [
'db1'=> [
'db' => 'testdb1',
'username' => 'user',
'password' => 'pass',
...
],
'db2'=> [...],
...
];
$seletected = 'db1';
$database = $databases[$selected];
$client = new MongoDB\Client(
"mongodb+srv://{$database['username']}:{$database['password']}@<cluster-address>/test?retryWrites=true&w=majority"
);
$db = $client->{$database['db']};