-->
➜ docker run --name mymongo -d -p 27017:27017 -e MONGO_INITDB_ROOT_USERNAME=mongoadmin -e MONGO_INITDB_ROOT_PASSWORD=secret mongo:3.6.17
➜ mongo --username mongoadmin --password secret
> show dbs
> db.getUsers()
> use somedb
> db.createUser({user:"myadmin",pwd:"nicetomeetyou",roles:[{role:"readWrite",db:"somedb"}]})
Successfully added user: {
"user" : "myadmin",
"roles" : [
{
"role" : "readWrite",
"db" : "somedb"
}
]
}
> db.auth("myadmin","nicetomeetyou")
$: mongosh -u myadmin -p nicetomeetyou --authenticationDatabase somedb
> db.users.getIndexes()
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "yourbiz.users"
},
{
"v" : 2,
"unique" : true,
"key" : {
"phone" : 1
},
"name" : "phone_1",
"ns" : "yourbiz.users",
"background" : true
},
{
"v" : 2,
"unique" : true,
"key" : {
"outId" : 1
},
"name" : "outId_1",
"ns" : "yourbiz.users",
"background" : true
}
]
>
> db.users.dropIndex('phone_1')
{ "nIndexesWas" : 4, "ok" : 1 }
$> mongodump --uri="mongodb://root:example@127.0.0.1:27017/somdb?authSource=admin&readPreference=primary&appname=MongoDB%20Compass&ssl=false"
$> mongorestore --uri="mongodb://root:example@127.0.0.1:27017/somdb?authSource=admin&readPreference=primary&appname=MongoDB%20Compass&ssl=false"
mongo --port=21017
即可登录,若想设置密码,则需要先登录上,并使用以下命令设置用户名和密码:> use admin
switched to db admin
> db.createUser({user:"myAdmin",pwd:"passwordYOuWant",roles:[{role:"userAdminAnyDatabase",db:"admin"}]})
Successfully added user: {
"user" : "myAdmin",
"roles" : [
{
"role" : "userAdminAnyDatabase",
"db" : "admin"
}
]
}
>
> db.auth("myAdmin","passwordYOuWant")
1
然后在配置文件中打开安全设置 :
security:
authorization: enabled
db.grantRolesToUser('myaccount',[{role:'readWrite',db:'somedb'}])