w3resource

MongoDB User Management Commands

Create New User - createUser Command

The createUser command is used to create a new user on the database where you run the command. The createUser command returns an error message if the user already exists.

A database name must have to mention at the time to create a new user with createUser action.

A grantRole action must have to mention on a role’s database to grant the role to another user.

If you have the userAdmin or userAdminAnyDatabase role, or if you are authenticated using the localhost exception, you have those actions.

Syntax:

{ createUser: "<name>",
  pwd: "<cleartext password>",
  customData: { <any information> },
  roles: [
    { role: "<role>", db: "<database>" } | "<role>",
    ...
  ],
  writeConcern: { <write concern> }
}			 

Parameters:

Name Type Description
createUser string The name of the new user.
pwd string The user’s password.
customData document Optional.
roles array The roles granted to the user
writeConcern document Optional. The write concern briefs the guarantee that MongoDB provides at the time of reporting on the success of a write operation. w: 1 as the default write concern.

Assume that our database name is userdetails and there are the following document:

db.userdetails.insert({"user_id" : "user1","password" :"1a2b3c" ,
"date_of_join" : "16/10/2010" ,"education" :"M.C.A." ,
 "profession" : "CONSULTANT","interest" : "MUSIC",
 "community_name" :["MODERN MUSIC", "CLASSICAL MUSIC","WESTERN MUSIC"],
 "community_moder_id" : ["MR. Alex","MR. Dang","MR Haris"],
 "community_members" : [700,200,1500],
 "friends_id" : ["kumar","harry","anand"],
 "ban_friends_id" :["Amir","Raja","mont"]});   

Example

The following createUser command creates a user myNewuser on the userdetails database. The command gives myNewuser the clusterAdmin and readAnyDatabase roles on the admin database and the readWrite role on the userdetails database:

db.getSiblingDB("userdetails").runCommand( { createUser: "myNewuser",
                                          pwd: "thisPassword",
                                          customData: { profession : "DOCTOR" },
                                          roles: [
                                                   { role: "clusterAdmin", db: "admin" },
                                                   { role: "readAnyDatabase", db: "admin" },
                                                   "readWrite"
                                                 ],
                                          writeConcern: { interest : "SPORTS" }
                                       } )             

Example: Create more user

The following createUser command creates a user myNewuser1 on the userdetails database. The command gives myNewuser1 the clusterAdmin and the readWrite role on the userdetails database:

db.getSiblingDB("userdetails").runCommand( { createUser: "myNewuser1",
                                          pwd: "thisPassword",
                                          customData: { profession : "DOCTOR" },
                                          roles: [
                                                   { role: "clusterAdmin", db: "admin" },
                                                   "readWrite"
                                                 ],
                                          writeConcern: { interest : "SPORTS" }
                                       } )             

If we type wrongly in the above statement myNewuser instead of myNewuser1 then the following error message as an output will appear beacuse the user already exists

{
        "ok" : 0,
        "errmsg" : "User \"myNewuser@userdetails\" already exists",
        "code" : 11000
}         

To see the User Information - usersInfo Command

The command usersInfo returns information about one or more users.

Syntax:

{ usersInfo: { user: <name>, db: <db> },
  showCredentials: <Boolean>,
  showPrivileges: <Boolean>
}			 

Parameters:

Name Type Description
usersInfo various The user(s) about whom to return information.
showCredentials Boolean Optional. If the field set to true the user’s password hash will be displayed, it is false by default.
showPrivileges Boolean Optional. If the field set to true to show the user’s full set of privileges, including expanded information for the inherited roles, it is false by default.

Example to View Specific User

To see information but not the credentials, for the user "myNewuser" defined in "userdetails" database, run the following command:

db.runCommand(
               {
                 usersInfo:  { user: "myNewuser", db: "userdetails" },
                 showPrivileges: false
               }
)     

Output:

{
        "users" : [
                {
                        "_id" : "userdetails.myNewuser",
                        "user" : "myNewuser",
                        "db" : "userdetails",
                        "customData" : {
                                "profession" : "DOCTOR"
                        },
                        "roles" : [
                                {
                                        "role" : "clusterAdmin",
                                        "db" : "admin"
                                },
                                {
                                        "role" : "readAnyDatabase",
                                        "db" : "admin"
                                },
                                {
                                        "role" : "readWrite",
                                        "db" : "userdetails"
                                }
                        ]
                }
        ],
        "ok" : 1
}    

Example to View Multiple User

To view info for several users, use an array, with or without the optional fields showPrivileges and showCredentials. For example:

db.runCommand( { usersInfo: [ { user: "myNewuser", db: "userdetails" }, 
                 { user: "myNewuser1", db: "userdetails" } ],
                 showPrivileges: false
                 } );     

Output:

{
        "users" : [
                {
                        "_id" : "userdetails.myNewuser",
                        "user" : "myNewuser",
                        "db" : "userdetails",
                        "customData" : {
                                "profession" : "DOCTOR"
                        },
                        "roles" : [
                                {
                                        "role" : "clusterAdmin",
                                        "db" : "admin"
                                },
                                {
                                        "role" : "readAnyDatabase",
                                        "db" : "admin"
                                },
                                {
                                        "role" : "readWrite",
                                        "db" : "userdetails"
                                }
                        ]
                },
                {
                        "_id" : "userdetails.myNewuser1",
                        "user" : "myNewuser1",
                        "db" : "userdetails",
                        "customData" : {
                                "profession" : "Engineer"
                        },
                        "roles" : [
                                {
                                        "role" : "clusterAdmin",
                                        "db" : "admin"
                                },
                                {
                                        "role" : "readWrite",
                                        "db" : "userdetails"
                                }
                        ]
                }
        ],
        "ok" : 1
}

Example to View All Users for a Database

To view all users on the database the following command can be used:

db.runCommand( { usersInfo: 1 , showCredentials : false} );   

Output:

{
        "users" : [
                {
                        "_id" : "userdetails.myNewuser",
                        "user" : "myNewuser",
                        "db" : "userdetails",
                        "customData" : {
                                "profession" : "DOCTOR"
                        },
                        "roles" : [
                                {
                                        "role" : "clusterAdmin",
                                        "db" : "admin"
                                },
                                {
                                        "role" : "readAnyDatabase",
                                        "db" : "admin"
                                },
                                {
                                        "role" : "readWrite",
                                        "db" : "userdetails"
                                }
                        ]
                },
                {
                        "_id" : "userdetails.myNewuser1",
                        "user" : "myNewuser1",
                        "db" : "userdetails",
                        "customData" : {
                                "profession" : "Engineer"
                        },
                        "roles" : [
                                {
                                        "role" : "clusterAdmin",
                                        "db" : "admin"
                                },
                                {
                                        "role" : "readWrite",
                                        "db" : "userdetails"
                                }
                        ]
                }
        ],
        "ok" : 1
}

If showCredential is true the output will be the following:

{
        "users" : [
                {
                        "_id" : "userdetails.myNewuser",
                        "user" : "myNewuser",
                        "db" : "userdetails",
                        "credentials" : {
                                "MONGODB-CR" : "28fcdbb5d879ccf086bd6404bd06b230"
                        },
                        "customData" : {
                                "profession" : "DOCTOR"
                        },
                        "roles" : [
                                {
                                        "role" : "clusterAdmin",
                                        "db" : "admin"
                                },
                                {
                                        "role" : "readAnyDatabase",
                                        "db" : "admin"
                                },
                                {
                                        "role" : "readWrite",
                                        "db" : "userdetails"
                                }
                        ]
                },
                {
                        "_id" : "userdetails.myNewuser1",
                        "user" : "myNewuser1",
                        "db" : "userdetails",
                        "credentials" : {
                                "MONGODB-CR" : "9b08b3a68eef34d462bdb2e5b2037438"
                        },
                        "customData" : {
                                "profession" : "Engineer"
                        },
                        "roles" : [
                                {
                                        "role" : "clusterAdmin",
                                        "db" : "admin"
                                },
                                {
                                        "role" : "readWrite",
                                        "db" : "userdetails"
                                }
                        ]
                }
        ],
        "ok" : 1
}

To Update the User Information - updateUser Command

The updateUser command updates the profile of the user on the specific database. This command completely replaces the data of the previous field’s values. It is required to specify the updateUser field and at least one other field, other than writeConcern to update a user.

Syntax:

{ updateUser: "<username>",
  pwd: "<cleartext password&glt;",
  customData: { <any information> },
  roles: [
    { role: "<role>", db: "<database>" } | "<role>",
    ...
  ],
  writeConcern: { <write concern> }
}		 

Parameters:

Name Type Description
updateUser string The name of the user to update.
pwd string Optional. The user’s password.
customData document Optional. Any arbitrary information.
roles array Optional. The roles granted to the user. An update to the roles array replace the values of the previous array.
writeConcern document Optional. The write concern briefs the guarantee that MongoDB provides at the time of reporting on the success of a write operation. w: 1 as the default write concern.

Example

Here in below a user myNewuser in the userdetails database with the following user info:

{
        "users" : [
                {
                        "_id" : "userdetails.myNewuser",
                        "user" : "myNewuser",
                        "db" : "userdetails",
                        "customData" : {
                                "profession" : "DOCTOR"
                        },
                        "roles" : [
                                {
                                        "role" : "clusterAdmin",
                                        "db" : "admin"
                                },
                                {
                                        "role" : "readAnyDatabase",
                                        "db" : "admin"
                                },
                                {
                                        "role" : "readWrite",
                                        "db" : "userdetails"
                                }
                        ]
                }
        ]
  }    

The following updateUser command completely replaces the user’s customData and roles data:

use userdetails
db.runCommand( { updateUser : "myNewuser",
                 customData : { profession : "Classical Music" },
                 roles : [
                           { role : "read", db : "assets"  }
                         ]
             } ) 

Here is the output after update the user:

> db.runCommand(
                {
                  usersInfo:  { user: "myNewuser", db: "userdetails" },
                 showPrivileges: false
               }
 );

{
        "users" : [
                {
                        "_id" : "userdetails.myNewuser",
                        "user" : "myNewuser",
                        "db" : "userdetails",
                        "customData" : {
                                "profession" : "Classical Music"
                        },
                        "roles" : [
                                {
                                        "role" : "read",
                                        "db" : "assets"
                                }
                        ]
                }
        ],
        "ok" : 1
}

To Drop the User Information - dropUser Command

The dropUser command is used to remove the user from the concern database.

Syntax:

{
  dropUser: "<user>",
  writeConcern: { <write concern> }
}

Parameters:

Name Type Description
dropUser string The name of the user to delete. This command will work only the database where the user exists.
writeConcern document Optional. The write concern briefs the guarantee that MongoDB provides at the time of reporting on the success of a write operation. w: 1 as the default write concern. .

Example

If we want to remove the user myNewuser1 from the userdetails database the following sequence of operations in the mongo shell can be used.

> use userdetails
switched to db userdetails
> db.runCommand( { dropUser: "myNewuser1"} );
  { "ok" : 1 }

Now if we want to view all the user for database userdetails the following result will appear where the user myNewuser1 will be excluded.

> db.runCommand( { usersInfo: 1 , showCredentials : false} );
{
        "users" : [
                {
                        "_id" : "userdetails.myNewuser",
                        "user" : "myNewuser",
                        "db" : "userdetails",
                        "customData" : {
                                "profession" : "Classical Music"
                        },
                        "roles" : [
                                {
                                        "role" : "read",
                                        "db" : "assets"
                                }
                        ]
                }
        ],
        "ok" : 1
}

To Drop All the Users Information - dropAllUsersFromDatabase Command

This command removes all users from the concern database on which you run the command.

Syntax:

{
dropAllUsersFromDatabase: 1,
 writeConcern: { <write concern> }
}

Parameters:

Name Type Description
dropAllUsersFromDatabase integer Specify 1 to drop all the users from the current database.
writeConcern document Optional. The write concern briefs the guarantee that MongoDB provides at the time of reporting on the success of a write operation. w: 1 as the default write concern.

Example

If we want to remove the user myNewuser1 from the userdetails database the following sequence of operations in the mongo shell can be used.

> use userdetails;
switched to db userdetails
> db.runCommand( { dropAllUsersFromDatabase: 1, writeConcern: { w: "majority" }});

Here is the output

{ "n" : 1, "ok" : 1 }

It means that the n field in the results document shows the number of users removed, here 1 user have been removed.

Now if we want to view the information of the user for database userdetails the following result will appear.

> db.runCommand( { usersInfo: 1 , showCredentials : false} );
{ "users" : [ ], "ok" : 1 }

To Grants additional roles to a user - grantRolesToUser Command

This command grants additional roles to a user.

Syntax:

{ grantRolesToUser: "<user>",
  roles: [ <roles> ],
  writeConcern: { <write concern> }
}

Parameters:

Name Type Description
grantRolesToUser string The name of the user to give additional roles.
roles array An array of additional roles to grant to the user.
writeConcern document Optional. The write concern briefs the guarantee that MongoDB provides at the time of reporting on the success of a write operation. w: 1 as the default write concern.

Example

Given a user myNewuser2 in the userdetails database with the following roles:

 {
                        "_id" : "userdetails.myNewuser2",
                        "user" : "myNewuser2",
                        "db" : "userdetails",
                        "customData" : {
                                "profession" : "painter"
                        },
                        "roles" : [
                                {
                                        "role" : "read",
                                        "db" : "usertransact"
                                },
                                {
                                        "role" : "readWrite",
                                        "db" : "userdetails"
                                }
                        ]
                }

The following grantRolesToUser operation gives myNewuser2 the read role on the usertransact database and the readWrite role on the userdetails database.

 {
                       "_id" : "userdetails.myNewuser2",
                       "user" : "myNewuser2",
                       "db" : "userdetails",
                       "customData" : {
                               "profession" : "painter"
                       },
                       "roles" : [
                               {
                                       "role" : "read",
                                       "db" : "usertransact"
                               },
                               {
                                       "role" : "read",
                                       "db" : "useraccount"
                               },
                               {
                                       "role" : "readWrite",
                                       "db" : "userdetails"
                               }
                       ]
               };

To Revoke Roles From a User - revokeRolesFromUser Command

This command is used to remove a one or more roles from a user on the database where the roles exist.

Syntax:

{ revokeRolesFromUser: "<user>",
  roles: [
    { role: "<role>", db: "<database>" } | "<role>",
    ...
  ],
  writeConcern: { <write concern> }
}

Parameters:

Name Type Description
revokeRolesFromUser string The user to remove roles from.
roles array The roles to revoke from the user.
writeConcern document Optional. The write concern briefs the guarantee that MongoDB provides at the time of reporting on the success of a write operation. w: 1 as the default write concern.

Example

Given a user myNewuser2 in the userdetails database with the following roles:

      {
                       "_id" : "userdetails.myNewuser2",
                       "user" : "myNewuser2",
                       "db" : "userdetails",
                       "customData" : {
                               "profession" : "painter"
                       },
                       "roles" : [
                               {
                                       "role" : "read",
                                       "db" : "usertransact"
                               },
                               {
                                       "role" : "read",
                                       "db" : "useraccount"
                               },
                               {
                                       "role" : "readWrite",
                                       "db" : "userdetails"
                               }
                       ]
               };

To remove the two of the user’s roles such as the read role on the usertransact database and the readWrite role on the userdetails database the following sequence of commands can be used.

use userdetails;
db.runCommand( { revokeRolesFromUser: "myNewuser2",
                 roles: [
                          { role: "read", db: "usertransact" },
                          "readWrite"
                 ],
                 writeConcern: { w: "majority" }
             } );

The user myNewuser2 in the userdetails database now has only one remaining role:

{
                        "_id" : "userdetails.myNewuser2",
                        "user" : "myNewuser2",
                        "db" : "userdetails",
                        "customData" : {
                                "profession" : "painter"
                        },
                        "roles" : [
                                {
                                        "role" : "read",
                                        "db" : "useraccount"
                                }
                        ]
                }

Previous: MongoDB count() cursor method
Next: Authentication Commands



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/mongodb/mongodb-user-management-commands.php