Create a MongoDB user from commandline

2020-07-02 09:51发布

问题:

I have set up a MongoDB database with an admin user that has only administrative rights, not read or write access to databases.

What I now would want to do is:

  • Add a new database,
  • and add a new user to that database.

And: I need to do this from the command line. So I tried:

$ mongo admin -u admin -p admin --eval "db.addUser('dummyuser', 'dummysecret')"

(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')"

just gives me syntax error.

How do I get this right?

回答1:

The use db syntax is only supported in an interactive shell session.

If you want to change databases from an admin script, you can use db.getSiblingDB('dbname').

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.



回答2:

Solved it by putting the commands

use dummydb
db.addUser('dummyuser', 'dummysecret')

into a .js file, and then ran MongoDB by calling:

$ mongo admin -u admin -p admin < setupMongoDB.js

That's it :-)



回答3:

Above in my case didn't worked

use dummyDb

db.createUser({user: "admin",pwd: "secrectP@wd",roles: [ { role: "readWrite", db: "reporting" } ],mechanisms: [ "SCRAM-SHA-256" ]   }


标签: mongodb