通常,命令行 连接 MongoDB 我们是这么做的:
mongo -u <user> -p <pass> --host <host> --port 28015
或者使用标准的连接字符串地址 URI:
mongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[database][?options]]
# 例如
mongo mongodb://127.0.0.1:27017
当连接主从数据库时候也可以直接使用,例如某些云服务器提供商的数据库连接方式:
mongo mongodb://root:password@dds-0xi1234.mongodb.rds.aliyuncs.com:3717,dds-0xi5678.mongodb.rds.aliyuncs.com:3717/admin
直接使用这种通用的地址字符串是非常方便的,不管是独立数据库、副本集以及集群都是统一的,格式大概是这样的:mongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[database][?options]]
但是,mongo 命令行客户端可以使用,其他的一些工具就没有办法直接用了,比如 mongotop
,mongofiles
等等:
# grid fs 操作
root@server:~# mongofiles mongodb://ubuntu:password@IP_ADDR:27017/admin
2019-08-12T20:39:52.764+0800 'mongodb://ubuntu:password@IP_ADDR:27017/admin' is not a valid command
2019-08-12T20:39:52.765+0800 try 'mongofiles --help' for more information
# mongo top
root@server:~# mongotop mongodb://ubuntu:password@IP_ADDR:27017/admin
2019-08-12T20:44:39.874+0800 invalid sleep time: mongodb://ubuntu:password@IP_ADDR:27017/admin
查了一下文档,阿里云上购买的这种叫做 Authentication Database¶
的数据库,需要使用 --authenticationDatabase
参数来操作:
Authentication Database 的说明是这样的:
Authentication Database¶
When adding a user, you create the user in a specific database. This database is the authentication database for the user.
A user can have privileges across different databases; that is, a user’s privileges are not limited to their authentication database. By assigning to the user roles in other databases, a user created in one database can have permissions to act on other databases. For more information on roles, see Role-Based Access Control.
The user’s name and authentication database serve as a unique identifier for that user. [1] That is, if two users have the same name but are created in different databases, they are two separate users. If you intend to have a single user with permissions on multiple databases, create a single user with roles in the applicable databases instead of creating the user multiple times in different databases.
对于这样的数据库,如果我们要使用 db 自带那一族工具来操作的话可以这样:
mongofiles --host dds-0xi1234.mongodb.rds.aliyuncs.com:3717 --authenticationDatabase admin -d xxx list
mongotop --host dds-0xi1234.mongodb.rds.aliyuncs.com:3717 --authenticationDatabase admin
mongostat --host dds-0xi1234.mongodb.rds.aliyuncs.com:3717 --authenticationDatabase admin