Creating first user in MongoDB 3.2.

2019-06-03 22:59发布

问题:

I newly installed MongoDB 3.2 and tried to create the first user which throws the following error.

" Error: couldn't add user: not authorized on admin to execute command"

I followed mongoDB 3.2 documentation, https://docs.mongodb.org/manual/tutorial/enable-authentication/

To add the administrator, I tried the following code which results in the above error

Create the user administrator. Add a user with the userAdminAnyDatabase role. For example, the following creates the user myUserAdmin on the admin database:

use admin
db.createUser(
  {
    user: "myUserAdmin",
    pwd: "MY_PASSWORD",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
  }
)

I gone through the other stackoverflow answers as well like but with no luck,

MongoDB - admin user not authorized

Update role user: not authorized on admin to execute command

My full error,

 E QUERY    [thread1] Error: couldn't add user: not authorized on admin to execute command { createUser: "myUserAdmin
", pwd: "xxx", roles: [ { role: "userAdminAnyDatabase", db: "admin" } ], digestPassword: false, writeConcern: { w: "majority", wtimeout: 30000.0
} } :
_getErrorWithCode@src/mongo/shell/utils.js:23:13
DB.prototype.createUser@src/mongo/shell/db.js:1225:11
@(shell):1:1

Thank you

回答1:

If you re-use an existing database directory /data/db, it is likely that previously there's already a user/auth set up.

You could either:

  • Start with a new database directory by pointing to a new data directory using --dbpath.
  • Run mongod without --auth, then

    use admin;
    db.getUsers(); // to see whether there's already an existing user. 
    

    Use db.removeUser() to remove existing users.