从命令行创建MongoDB用户 [英] Create a MongoDB user from commandline
问题描述
我用admin
用户建立了一个MongoDB数据库,该用户仅具有管理权限,对数据库没有读或写访问权限.
I have set up a MongoDB database with an admin
user that has only administrative rights, not read or write access to databases.
我现在想做的是:
- 添加新数据库,
- 并将新用户添加到该数据库.
而且:我需要从命令行执行此操作.所以我尝试了:
And: I need to do this from the command line. So I tried:
$ mongo admin -u admin -p admin --eval "db.addUser('dummyuser', 'dummysecret')"
(请注意,由于我仍在运行MongoDB 2.0,因此我使用的是db.addUser
的旧格式.)
(Please note that as I am still running MongoDB 2.0, I am using the old format of db.addUser
.)
如果我还可以告诉它该用户应该用于哪个数据库,这将是非常合理的.但是现在我在挣扎.如何为此命令指定数据库?如果我在交互式外壳中,我可以运行
This would make perfect sense if I could also tell it which database this user should be for. But now I am struggling. How do I specify the database for this command? If I were in the interactive shell, I could just run
> use dummydb
但是如何从命令行执行此操作?我的第一个尝试是用;
连接这两个命令,但这没有用:
but how do I do this from the command line? My first try was to concatenate both commands with a ;
, but this didn't work:
$ mongo admin -u admin -p admin --eval "use dummydb;db.addUser('dummyuser', 'dummysecret')"
只是给我语法错误.
我该如何正确处理?
推荐答案
仅在交互式Shell会话中支持use db
语法.
The use db
syntax is only supported in an interactive shell session.
如果要通过管理脚本更改数据库,则可以使用 db.getSiblingDB('dbname')
.
If you want to change databases from an admin script, you can use db.getSiblingDB('dbname')
.
因此,使用--eval
的等效命令行为:
So your equivalent command line using --eval
would be:
# MongoDB 2.6+: use createUser()
$ mongo admin -u admin -p admin --eval "db.getSiblingDB('dummydb').createUser({user: 'dummyuser', pwd: 'dummysecret', roles: ['readWrite']})"
# MongoDB 2.4: use addUser()
$ mongo admin -u admin -p admin --eval "db.getSiblingDB('dummydb').addUser('dummyuser', 'dummysecret')"
There is a section in the MongoDB manual covering Differences between interactive and scripted mongo
. This includes equivalents for other interactive shell helpers such as show dbs
and show collections
.
这篇关于从命令行创建MongoDB用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!