Create a MongoDB user from commandline

后端 未结 3 852
悲哀的现实
悲哀的现实 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.

    0 讨论(0)
  • 2021-02-19 05:26

    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 :-)

    0 讨论(0)
  • 2021-02-19 05:27

    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" ]   }
    
    0 讨论(0)
提交回复
热议问题