Create user and add role in MongoDB - GeeksforGeeks

18 Apr, 2022
In MongoDB, we are allowed to create new users for the database. Every MongoDB user only accesses the data that is required for their role. A role in MongoDB grants privileges to perform some set of operations on a given resource. In MongoDB, users are created using createUser() method. This method creates a new user for the database, if the specified user is already present in the database then this method will return an error.
Syntax:
 db.createUser(user, writeConcern)
Parameters: 
1. user: It contains authentication and access information about the user to create. It is a document.
user: Name of the user
pwd: User password. This fieid is not required if you use this method on $external database to create a user whose credentials are stored externally. The value of this field can be of string type or passwordPrompt().
customData: User Associative Information. It is an optional field.
roles: Access Level or Privilege of a user. You can also create a user without roles by passing an empty array[]. In this field, you use built-in roles or you can create you own role using db.createRole(role, writeConcern) method. To specify the roles you can use any of the following syntax:
Simply specify the role name:
 “read”
Or you can specify a document that contains the role and db fields. It is generally used when the role is specified in a different database.
{role:<role>, db: <database>}
authenticationRestrictions: Authentication permission of the user. It is an optional field.
mechanisms: It is used to specify the SCRM mechanisms or mechanisms for creating SCRM user credentials. It is an optional field.
passwordDigestor: It is used to check whether the server or client digest the password. It is an optional field.
2. writeConcern: It is an optional parameter. It manages the level of Write Concern for the creation operation. It takes the same field as the getLastError Command takes. 
Notes:
In MongoDB, the first created user in the database must be the admin user. The admin user has the privileges to maintain all the users. Also, you are not allowed to create users in the local database.
db.createUser() Sends Password And All Other Data to The MongoDB Instance Without Any Encryption. To Encrypt the Password During Transmission, Use TLS/SSL In order To Encrypt It.
In MongoDB, you can create an administrative user using the createUser() method. In this method, we can create the name, password, and roles of an administrative user. Let us discuss this concept with the help of an example:
Example:
In this example, we are going to create an administrative user in the admin database and gives the user readWrite access to the config database which lets the user change certain settings for sharded clusters.
db.createUser(
{ 
 user: "hello_admin",
 pwd:  "hello123",
 roles:
 [
 { role:"readWrite",db:"config"},
 "clusterAdmin"
 ] } );
So to create an administrative user first we use the admin database. In this database, we create an admin user using the createUser() method. In this method, we set the user name is “hello_admin”, password is “hello123” and the roles of the admin user are readWrite, config, clusterAdmin. 
In MongoDB, we can create a user without any roles by specifying an empty array[] in the role field in createUser() method.
Syntax:
db.createUser({ user:”User_Name”, pwd:”Your_Password”, roles:[]});
Let us discuss this concept with the help of an example:
Example:
In the following example, we are going to create a user without roles.
db.createUser({user:"geeks", pwd: "computer", roles:[]});
Here, we are working on the “example” database and created a user named “geeks” without roles.
In MongoDB, we can create a user with some specified roles using the createUser() method. In this method, we can specify the roles that the user will do after creating. Let us discuss this concept with the help of an example:
Example:
In this example, we are going to create a user with some specified roles.
db.createUser(
...{
...user: "new_one_role",
...pwd: with_roles",
...roles:["readWrite", "dbAdmin"]
...}
...);
Here, we create a user whose name is “new_one_role”, password is “with_roles” and the specified roles are:
readWrite Role: This role provides all the privileges of the read role plus the ability to modify data on all non-system collections.
dbAdmin Role: This role gives the ability to the user to perform administrative tasks such as schema-related tasks, indexing. It does not grant privileges for the User and Role Management.
In MongoDB, we can also create a user for single database using createUser() method. Let us discuss this concept with the help of an example:
Example:
db.createUser(
{
user: "robert",
pwd:  "hellojose",
roles:[{role: "userAdmin" , db:"example"}]})
Here, we create a user whose user name is “Robert”, password is “hellojose”, and we assign a role for the user which in this case needs to be a database administrator so it is assigned to the “userAdmin” role. This role will allow the user to have administrative privileges only to the database specified in the db option, i.e., “example”.
In MongoDB, authentication is a process which checks whether the user/client who is trying to access the database is known or unknown. If the user is known then it allows them to connect with server. We can also create a user with authentication restrictions using createUser() method by setting the value of authenticationRestrictions field. This field provides authentication permission of the user and contains the following fields:
clientSource: If the value of this field is present, so when a user is authenticating the server verifies the client IP by checking the IP address in the given list or CIDR range in the list. If the client IP present in the list then the server authenticate the client or if not then server will not authenticate the user.
serverAddress: It is a list of IP addresses or CIDR ranges to which the client can connect. If the value of this field is present in the list, then the server verify the client connection and if the connection was established via unrecognized IP address, then the server does not authenticate the user.
Let us discuss this concept with the help of an example:
Example:
In this example, we are going to create a user with authentication restrictions:
use admin
db.createUser(
   {
     user: "restrict",
     pwd: passwordPrompt(),      
     roles: [ { role: "readWrite", db: "example" } ],
     authenticationRestrictions: [ {
        clientSource: ["192.168.65.10"],
        serverAddress: ["198.157.56.0"]
     } ]
   }
)
Here we create a user named “restrict” in the admin database. So this user may only authenticate if connecting from IP address 192.168.65.10 to this server address IP address 198.157.56.0.
In Mongodb, we can also drop a user using dropUser() method. This method returns true when the user is deleted otherwise return false.
Syntax:
db.dropUser(“Username”)
Example:
In this example, we will drop a user whose name is Robert.
db.dropUser("robert")
anikakapoor
MongoDB
Picked
MongoDB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
MongoDB - Distinct() Method
How to connect MongoDB with ReactJS ?
MongoDB - limit() Method
MongoDB - FindOne() Method
MongoDB insertMany() Method - db.Collection.insertMany()
MongoDB updateOne() Method - db.Collection.updateOne()
MongoDB - Update() Method
MongoDB - sort() Method
MongoDB Cursor
MongoDB updateMany() Method - db.Collection.updateMany()