我正在尝试添加授权到我的MongoDB。 我使用MongoDB 2.6.1在Linux上完成所有这些工作。 我的mongo .conf文件是旧的兼容格式 (这就是安装的方式)。

1)我创建了admin用户,如(3)所述

http://docs.mongodb.org/manual/tutorial/add-user-administrator/

2)然后我通过取消注释这一行来编辑mongo .conf

真实的

3)最后,我重启了mongod服务,并尝试登录:

/usr/bin/mongo localhost:27017/admin -u sa -p PWD

4)我可以连接,但它说这个连接。

MongoDB shell version: 2.6.1
connecting to: localhost:27017/admin
Welcome to the MongoDB shell!
The current date/time is: Thu May 29 2014 17:47:16 GMT-0400 (EDT)
Error while trying to show server startup warnings: not authorized on admin to execute command { getLog: "startupWarnings" }

5)现在我创建的sa用户似乎没有任何权限。

root@test02:~# mc
MongoDB shell version: 2.6.1
connecting to: localhost:27017/admin
Welcome to the MongoDB shell!
The current date/time is: Thu May 29 2014 17:57:03 GMT-0400 (EDT)
Error while trying to show server startup warnings: not authorized on admin to execute command { getLog: "startupWarnings" }
[admin] 2014-05-29 17:57:03.011 >>> use admin
switched to db admin
[admin] 2014-05-29 17:57:07.889 >>> show collections
2014-05-29T17:57:10.377-0400 error: {
        "$err" : "not authorized for query on admin.system.namespaces",
        "code" : 13
} at src/mongo/shell/query.js:131
[admin] 2014-05-29 17:57:10.378 >>> use test
switched to db test
[test] 2014-05-29 17:57:13.466 >>> show collections
2014-05-29T17:57:15.930-0400 error: {
        "$err" : "not authorized for query on test.system.namespaces",
        "code" : 13
} at src/mongo/shell/query.js:131
[test] 2014-05-29 17:57:15.931 >>>

有什么问题吗?我把整个过程重复了三次 我想我做的都是在MongoDB文档中指定的。但这并不奏效。 我期望这个sa用户被授权做任何事情,以便 然后,他可以创建其他用户,并给予他们更具体的权限。


当前回答

此外,请注意,如果您的mongo shell客户端无法正确连接到mongod实例,您可能会收到这样的“Permission Denied”错误。

确保您的客户端通过检查连接端口打开了一个连接,同时还要检查您在mongod中使用的端口没有被使用。您可以在shell和进程中使用——port <port>参数来设置不同的端口。

其他回答

如果使用Atlas,请注意不能通过mongo shell创建用户。

我一直在用头撞墙,直到我看到了这个: https://www.mongodb.com/community/forums/t/cant-create-a-root-user-from-mongo-shell/101369

同意你必须获得身份验证到admin db,并且至少需要一个具有正确权限的角色,以避免来自db的“本地主机异常”(这是mongoDB的托管在本地),尽管你已经一切就绪,但仍然在几乎每个命令上获得未授权的异常,而访问mongoDB时使用Mongo Atlas创建,然后在这里你可能知道原因,为什么:

https://dba.stackexchange.com/questions/219003/not-authorized-on-admin-to-execute-command-mongodb-atlas-m0-free-tier-cluster?newreg=471a9a26108243d78d4ca74a87e7a115

如果你在mongo Atlas上托管了mongoDB,也要检查一下:

https://docs.atlas.mongodb.com/unsupported-commands/

这是个简单的问题。

必须切换目标db而不是admin,这一点很重要。

使用yourDB

检查您的db身份验证

显示用户

如果你得到一个{}空对象,那就是问题。你只需要打字

db createUser。( { 用户:“yourUser”, pwd:“密码”, roles: ["readWrite", "dbAdmin"] })

or

db。grantRolesToUser('yourUser',[{role: ' dbAdmin ', db: ' yourDB}])

我在Windows环境中遇到了类似的问题:我已经安装了Bitnami DreamFactory,它还安装了另一个MongoDb,在系统引导时启动。我正在运行我的MongoDbService(启动时没有任何错误),但我注意到在浪费了很多时间后,我实际上是在Bitnami的MongoDb服务上连接。请检查一下,如果您的服务器上没有另一个mongoDB实例正在运行。

好运!

对于MongoDB shell版本v4.2.8,我已经尝试了不同的方法来备份我的数据库与认证,我的赢家解决方案是

mongodb -h <your_hostname> -d <your_db_name> -u <your_db_username> -p <your_db_password>——authenticationDatabase admin -o /path/to/where/i/want . sh