這個文檔挺好的https://blog.csdn.net/u010523770/article/details/54599548
先添加超級使用者:
use admindb.createUser( { user: "admin", pwd: "password", roles: [ { role: "root", db: "admin" } ] });exit;
mongodb 3添加新使用者:db.createUser( { "user" : "test1",
"pwd": "test1",
"customData" : { employeeId: 12345 },
"roles" : [ { role: "clusterAdmin", db: "admin" },
{ role: "readAnyDatabase", db: "admin" },
"readWrite"
] },
{ w: "majority" , wtimeout: 5000 } )
轉載來源:http://www.cnblogs.com/zj1111184556/p/3599828.html
安裝 MongoDB
sudo apt-get install mongodb
sudo apt-get install mongodb
使用者操作(2.4.9上面測試的):
mongo
user admin;
db.auth('', '');
db['system.users'].find({}, {user:1, pwd:1, _id: 0});
刪除一個使用者:
db.removeUser('root2')
修改一個使用者的密碼:
db.changeUserPassword("accountUser", "SOh3TbYhx8ypJPxmt1oOfL")
關閉/啟動
sudo service mongodb stop
sudo service mongodb start
設定資料庫連接密碼:
在跟目錄建立檔案夾: data/db
關閉現有服務。
sudo service mongodb stop
重新啟動服務
$ mongod –auth
建立串連使用者
$ mongo
> use admin
switched to db admin
> db.addUser("root","1983")
關閉服務(直接在 mongod 啟動的命令視窗 “ctrl + C”)
重啟服務:
$: mongod –auth
查看是否開始驗證:、
$ mongo
MongoDB shell version: 2.0.4
connecting to: test
> use admin
switched to db admin
> show collections
Fri Mar 14 09:07:08 uncaught exception: error: {
"$err" : "unauthorized db:admin lock type:-1 client:127.0.0.1",
"code" : 10057
}
有提示 連結錯誤。
進行使用者驗證:
> db.auth("root","1983")
1
重新查看就可以查看資料集
> show collections
system.indexes
system.users
設定用戶端串連:
預設安裝的話只允許 127.0.0.1 的IP 串連.
需要修改/etc/mongodb.conf 注釋下列記錄:
開啟檔案:
$ sudo gedit /etc/mongodb.conf
注釋記錄:
#bind_ip = 0.0.0.0
mongodb 2.6以後的版本添加使用者方法,每個庫需要授權才能訪問:
https://docs.mongodb.org/manual/reference/method/db.createUser/
use productsdb.createUser( { user: "accountUser", pwd: "password", roles: [ "readWrite", "dbAdmin" ] })
在centos6.5上面安裝後建立 使用者後串連報錯,查看日誌mongodb.log:
AuthenticationFailed: MONGODB-CR credentials missing in the user document
非常感覺此哥vivek(http://stackoverflow.com/users/2512718/vivek)的回答:
http://stackoverflow.com/questions/29006887/mongodb-cr-authentication-failed
go to mongoDB console and delete your current user & set authSchema version to 3 instead of 5 , follow these commands in mongo console -
mongo
use admin
db.system.users.remove({}) <== removing all users
db.system.version.remove({}) <== removing current version
db.system.version.insert({ "_id" : "authSchema", "currentVersion" : 3 })
Now restart the mongod and create new user then it should work fine.
Note: use remove commands in test db only, if in production use update.
重啟mongodb後再用下面的命令建立使用者,就正常:
db.createUser(
{
user: "username",
pwd: "passwd",
roles: [ "readWrite", "dbAdmin" ]
}
)
=========================
db.createUser(
{
user: "11",
pwd: "11",
roles: [ {role: "userAdminAnyDatabase", db: "admin"} ]
}
)
admin庫:
db.grantRolesToUser(
"admin",
[
{role: "readWrite", db: "admin"} ,
{role: "readAnyDatabase", db: "admin"} ,
]
)
普通庫
db.grantRolesToUser(
"admin",
[
{role: "readWrite", db: "test"} ,
{role: "readWrite", db: "files"} ,
]
)
設定自動啟動:
update-rc.d mongodb defaults