从命令行创建MongoDB用户 [英] Create a MongoDB user from commandline

查看:327
本文介绍了从命令行创建MongoDB用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用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')"

MongoDB手册中有一节涵盖了

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆