MongoDB PHP定义数据库连接


MongoDB PHP define database connection

我使用这种方法连接到远程数据库:(SSH隧道在后台运行)

$mongo = new Mongo('mongodb://[root:password]@localhost:27018');

然而,我得到这样的错误:

致命错误:未捕获异常"MongoConnectionException",带有消息'无法连接到:localhost:27018:SASL身份验证在数据库"admin"上失败:身份验证失败在里面/var/www/html/mongo_seed/index.php:22堆栈跟踪:#0/var/www/html/mongo_seed/index.php(22):Mongo->__construct('mongodb://[root…')#1{main}被抛出/第22行上的var/www/html/mongo_seed/index.php

如何在参数字符串中定义要连接到哪个数据库?否则,我该如何一个方法一个方法地完成整个过程?

MongoDB规范说:

mongodb://[用户名:密码@]host1[:端口1][,host2[:端口2],。。。[,hostN[:端口N]][/[数据库][?选项]]

https://docs.mongodb.com/manual/reference/connection-string/

我想你只需要补充一下/databasename在最后?

$connection = new MongoClient( "mongodb://[root:password]@localhost:27018" );

使用这个。