記錄一下,MongoDB的角色創建及配置,以便以后使用
1.1、基本知識介紹
MongoDB基本的角色
1.數據庫用戶角色:read、readWrite;
2.數據庫管理角色:dbAdmin、dbOwner、userAdmin;
3.集群管理角色:clusterAdmin、clusterManager、clusterMonitor、hostManager;
4.備份恢復角色:backup、restore;
5.所有數據庫角色:readAnyDatabase、readWriteAnyDatabase、userAdminAnyDatabase、dbAdminAnyDatabase
6.超級用戶角色:root
//這里還有幾個角色間接或直接提供了系統超級用戶的訪問(dbOwner 、userAdmin、userAdminAnyDatabase)
其中MongoDB默認是沒有開啟用戶認證的,也就是說游客也擁有超級管理員的權限。userAdminAnyDatabase:有分配角色和用戶的權限,但沒有查寫的權限
1.2、操作步驟
1.2.1、連接到MongoDB服務器
./mongo
1.2.2、創建root/admin用戶
use admin
db.createUser({user:"root",pwd:"password",roles:["root"]})
db.createUser(
{
user: "admin",
pwd: "password",
roles: [{role: "userAdminAnyDatabase", db: "admin"}]
}
)
1.2.3、修改mongod.conf文件
security: authorization: enabled//啟用授權
1.2.4、重啟MongoDB服務器
service mongod restart
1.2.5、創建數據庫讀寫權限用戶
use admin
db.auth("admin","password");
use ballmatch
db.createUser({
user: "football",
pwd: "password",
roles: [{role: "readWrite",db: "ballmatch"}]
})
1.2.6、Java程序連接MongoDB
//方式一 MongoCredential credential = MongoCredential.createCredential("username", "dbName", "password".toCharArray()); ServerAddress serverAddress = new ServerAddress("192.168.10.242", 27017); MongoClient mongoClient = new MongoClient(serverAddress, Arrays.asList(credential)); DB db = mongoClient.getDB("dbName"); returndb; //方式二 String sURI = String.format("mongodb://%s:%s@%s:%d/%s", "username", "password", "192.168.10.242", 27017, "dbName"); MongoClientURI uri = new MongoClientURI(sURI); MongoClient mongoClient = new MongoClient(uri); DB db = mongoClient.getDB("dbName");
2、命令參考
3.1、修改用戶密碼
db.updateUser( "admin",{pwd:"password"});
3.2、密碼認證
db.auth("admin","password");
3.3、MongoDB連接信息查詢
db.serverStatus().connections;
MongoDB實例接受的最多連接數,如果高於操作系統接受的最大線程數,設置無效。net.maxIncomingConnections默認(65536)
3.4、關閉MongoDB服務
use admin; db.shutdownServer();
3.5、刪除用戶
刪除用戶(需要root權限,會將所有數據庫中的football用戶刪除)
db.system.users.remove({user:"football"});
刪除用戶(權限要求沒有那么高,只刪除本數據中的football用戶)
db.dropUser("football");
