Search code examples
mongodbmongodb-security

How to create user with read-write access for specific DB only in MongoDB?


I've created user by shell:

use testDB
db.createUser({user: 'testUser', pwd: 'password', roles: ["readWrite"]})

But the user can see and modify another databases also (like admin). I've checked by db.runCommand({connectionStatus : 1}) and 'testUser' is logged in the session.

How to create user with read-write access just for specific database?


Solution

  • You can perform all user maintenance in admin database namespace. So, for your case, you can run following commands from your mongo shell:

    use admin
    
    db.createUser({
      user: "testUser",
      pwd: "password",
      roles: [
        { role: "readWrite", db: "<your_database>" }
      ]
    })
    

    More details can be found at MongoDB documentation: https://docs.mongodb.com/manual/reference/method/db.createUser/