添加管理员:
> db.createUser(
{
user:"root",
pwd:"password",
roles:[
{role:"root",db:"admin"}
]
})
Successfully added user: {
"user" : "root",
"roles" : [
{
"role" : "root",
"db" : "admin"
}
]
}
修改mongod.conf配置文件,添加一行:auth=true,然后重启数据库。
再次尝试登录:
[root@localhost ~]# mongo
MongoDB shell version: 2.6.11
connecting to: test
> show collections
2015-10-09T17:05:29.192+0800 error: {
"$err" : "not authorized for query on test.system.namespaces",
"code" : 13
} at src/mongo/shell/query.js:131
>
此处出现错误。可以通过下面步骤正确使用mongodb:
> use admin
switched to db admin
> db.auth("root","password")
1
> use libraray
switched to db libraray
> show collections
audit
fs.chunks
fs.files
media
system.indexes
> db.media.find()
{ "_id" : ObjectId("561616d162e036b93305b524"), "Type" : "Book", "Title" : "Definitive Guide to MongoDB 2nd ed.
对于GridFS的mongofiles客户端来说最好创建一个额外的用户,否则将无法查询相关文件。
db.createUser(
{
user:"libraray",
pwd:"password",
roles:[
{role:"readWrite",db:"libraray"}
]
})
[root@localhost ~]# mongofiles search zip -d libraray -u "libraray" -p "password"
connected to: 127.0.0.1
2290944.zip 3372909855
如果使用root用户:
[root@localhost ~]# mongofiles search zip -d libraray -u "root" -p "password"
connected to: 127.0.0.1
assertion: 18 { ok: 0.0, errmsg: "auth failed", code: 18 }
或者使用authenticationDatabase选项,如:
[root@localhost ~]# mongofiles search zip -d libraray -u "root" -p "password" --authenticationDatabase admin
connected to: 127.0.0.1
2290944.zip 3372909855