How to Add Permissions or Role to Existing User in MongoDB

In this blog we will learn, how to add permission or role in existing User. In this we will use db.updateUser() method to update the user’s profile on the database on which you run the method. An update to a field completely replaces the previous field’s values. This includes updates to the user’s roles array.

Steps to update the user permission:

Step 1: First we will check the current permission on users:

1use admin;
2db.getUsers();

Step 2: Update the user :

MongoDB db.updateUser() method Syntax:

 1db.updateUser(
 2   "<username>",
 3   {
 4     customData : { <any information> },
 5     roles : [
 6               { role: "<role>", db: "<database>" } | "<role>",
 7               ...
 8             ],
 9     pwd: "<cleartext password>"
10    },
11    writeConcern: { <write concern> }
12)

Example:

1    db.updateUser( "user-name",
2       {
3    
4     roles : [
5              { role : "readWrite", db : "db1"  },
6              { role : "read", db : "db2"  }
7            ]
8       }
9    )

Note: To learn more on role click on link

I :heart: AWS! :smile: Enjoy