- 公司用了阿里云的MongoDB服务也用了手动安装的原生MongoDB,记录一下。
- 阿里云的MongoDB只能在阿里云的服务器上连接!如:我本地电脑装了Ubuntu,在自己的Ubuntu下使用shell无法连上在阿里云的MongoDB。
- 连接阿里云的MongoDB需使用MongoDB 3.0以上版本的driver。
1.连接阿里云MongoDB
①.shell连接阿里云MongoDB,连接命令可在阿里云控制台查看。使用shell必须对用户做授权。不然无法操作数据库做curd。
mongo --host dds-2z2f5a7b4f6588f41.mongodb.rds.aliyuncs.com:3718 --authenticationDatabase admin -u username -p passwrod
②.PHP7连接阿里云MongoDB,同样连接命令可在阿里云控制台查看。如下PHP代码就已经连接了数据库“my_database”。
$db = (new \MongoDB\Client("mongodb://username:password@dds-2z2f5a7b4f6588f41.mongodb.rds.aliyuncs.com:3718,dds-2z2f5a7b4f6588f42.mongodb.rds.aliyuncs.com:3718/admin?replicaSet=mgset-3420"))->selectDatabase('my_database');
2.连接原生MongoDB
①shell连接
mongo --host 121.8.162.82:3000 -u "username" -p "password" --authenticationDatabase "admin"
如下方式也可以,先连接。数据库,再做权限认证。
mongo --host 121.8.162.82:3000;
use admin
db.auth("username","password")
若登录后不做认证,使用show dbs等命令就会报错。
>show dbs
2017-06-05T18:21:34.317+0800 E QUERY Error: listDatabases failed:{
"ok" : 0,
"errmsg" : "not authorized on admin to execute command { listDatabases: 1.0 }",
"code" : 13
}
②PHP7连接
$db = (new \MongoDB\Client("mongodb://username:password@121.8.162.82:3000/admin"))->selectDatabase('my_database');