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

7.3k Views Asked by At

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?

1

There are 1 best solutions below

0
On BEST ANSWER

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/