MongoDB在shell以及PHP 中连接方式

  • 公司用了阿里云的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');
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值