0

We are using MONGO DB with PHP(Version 7.xx) and recently we applied authentication to MongoDB.

We have used config "mongodb://IP address:Port" to connect to MongoDB, and we changed it to "mongodb://user_name:password@IP:PORT".

When I try to connect DB URL with DB NAME like "mongodb://user_name:password@IP:PORT/DB NAME", It's work. but when without DB NAME like "mongodb://user_name:password@IP:PORT", Authentication failed error returend.

I'd like to know How to connect to All DBS by MongoDB URL.

Any helps are welcome.

Nick
  • 52
  • 2
  • 7
  • When you connect to Mongo then you can specify the authentication database and the database you like to work with. Have a look at this one: https://stackoverflow.com/questions/63754742/authentication-failure-while-trying-to-save-to-mongodb/63755470#63755470 – Wernfried Domscheit Oct 27 '20 at 07:19

1 Answers1

-1

you can refer my code:

private static function getMongoConfiguration(string $host, int $port, string $user, string $password,
                                                  bool $isReplica, string $replicaSetName = "rs0", array $replicaConfigs = [])
    {
        $params = [];
        $mgDb = "mongodb://" . $user . ":" . $password;
        if (!$isReplica){
            $mgDb = $mgDb. "@". $host . ":" . $port;
        }else{
            $params = [
                "replicaSet" => $replicaSetName,
                "db" => $database
            ];

            $c = 1;
            foreach ($replicaConfigs as $dbToUse) {
                $mongoHost = isset($dbToUse["host"]) ? $dbToUse["host"] : $port;
                $mongoPort = isset($dbToUse["port"]) ? $dbToUse["port"] : $port;
                $new = $mongoHost . ":" . $mongoPort;
                $mgDb = ($c > 1) ? $mgDb . "," . $new : $mgDb . $new;
                $c++;
            }
        }
        return [$mgDb, $params];
    }

then you create the Client to interact with MongoDb

$mongo = new Client($mgDb, $params);
// interact with 'app' database ...
$dbName = 'app';
$db = $mongo->{$dbName};

note: I use the https://packagist.org/packages/mongodb/mongodb as high-level abstraction of Php Mongo driver

Erics Nguyen
  • 370
  • 4
  • 16