How to create read-only access for a user in MongoDB
Introduction:
In MongoDB, you can create read-only access for users by assigning appropriate roles that grant read-only privileges to the user. MongoDB provides several built-in roles that can be used to grant read-only access. The two most common built-in roles for read-only access are read and readAnyDatabase.
Prerequisite:
- Server root login credentials.
- Mongo DB credentials if it is authenticated.
Step 1:
Log in to your Ubuntu or Centos server as a user with sudo privileges.
$ ssh root@Ip |
Login to Mongo Shell. If authenticated, please follow the below steps.
Then use admin.
$ mongo or $ mongo -u username -p –authenticationDatabase admin $ use admin |
To create the read-only user.
$ db.createUser({ user: “testuser”, pwd: “password “, roles: [ { role: “dbAdmin”, db: “database” }, { role: “readAnyDatabase”, db: “admin” } ] }) |
Authenticate the user. If authentication is successful, the result will be 1. If authentication fails, you get an error.
$ db.auth(‘testuser’,’password’) $ exit |
$mongo -u testuser -p or $ mongo -u testuser -p –authenticationDatabase admin |
Following the steps mentioned above, we can create read-only access for users in MongoDB.