John Davidson

php - Retrieve MongoDB\Client from \MongoDB\Driver\Manager

0 comments
Message:


I use \MongoDB\Driver\Manager to manage my connections, but I do not use MongoDB\Client.
I'm trying to list databases given a connection but the method listDatabases is only available via MongoDB\Client.


The documentation states



MongoDB\Client is analogous to the driver’s MongoDB\Driver\Manager
class, which it composes.



How do I list databases from an instance of \MongoDB\Driver\Manager ?



My Answer:
Unfortunately, the \MongoDB\Driver\Manager class does not have a method to list databases directly. The \MongoDB\Driver\Manager class is meant for managing connections to the MongoDB server and executing commands, while the \MongoDB\Client class is used for interacting with databases and collections.

If you want to list databases using the \MongoDB\Driver\Manager class, you will need to execute the listDatabases command directly using the command method of the manager object. Here is an example of how you can do this:

php

$manager = new \MongoDB\Driver\Manager("mongodb://localhost:27017");

$command = new \MongoDB\Driver\Command(['listDatabases' => 1]);
$cursor = $manager->executeCommand('admin', $command);

$response = current($cursor->toArray());
$databases = $response->databases;

foreach ($databases as $database) {
echo $database->name . "\n";
}


In this example, we create a new \MongoDB\Driver\Command object with the listDatabases command and execute it using the executeCommand method of the manager object. We then iterate over the list of databases returned in the response and print out their names.

Please note that using the \MongoDB\Driver\Manager class directly like this is more low-level and requires you to manually handle the responses and commands. It is recommended to use the \MongoDB\Client class for higher-level operations like listing databases.

Rate this post

5 of 5 based on 2793 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us