1.使用admin数据库
> use admin
2.创建用户函数crateUser()
> db.createUser(
... {
... user: "username",
... pwd: "password",
... roles: [
... { role: "readWrite", db: "testdb_one" }, # 在当前库下创建其他库的帐号,在admin库下创建test库的帐号
... { role: "readWrite", db: "testdb_two" }
... ]}
... )
> show users; # 显示所有用户
> use admin # 只能在帐号创建库下认证,再去其他库进行操作
> db.auth('username','password') # 验证
3.操作数据库,写入数据
> use testdb_one
> db.collection.insert({"a":1111,"b":2222})
> use testdb_two
> db.collection.insert({"a":1111,"b":2222})
ps: 代码操作用户认证连接到数据库
from pymongo import MongoClient
client = MongoClient("mongodb://username:password@127.0.0.1:27017/")
db = client["testdb_one"]
collections = db["test_collection"]
远程连接失败解决:
1.关闭防火墙
[root@localhost ~]# systemctl stop firewalld
2.任意ip可访问方式 启动
[root@localhost bin]# ./mongod --bind_ip=0.0.0.0 --port=27017