Create a MongoDB user from commandline

后端 未结 3 856
悲哀的现实
悲哀的现实 2021-02-19 04:23

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

3条回答
  •  鱼传尺愫
    2021-02-19 05:26

    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.

提交回复
热议问题