MongoDB Create User

This tutorial covers how to create MongoDB User. createUser() method is used to create MongoDB User. We are going to create user with roles and without roles.

MongoDB Create User Syntax:

{ user: "", pwd: "", customData: { }, roles: [ { role: "", db: "" } | "", ... ], authenticationRestrictions: [ { clientSource: ["" | "", ...] serverAddress: ["" | "", ...] }, ... ], mechanisms: [ "", ... ], passwordDigestor: "" }

Required permissions for MongoDB Create User:

  • To create a new user in a database, you must have the createUser action on that database resource.
  • To grant roles to a user, you must have the grantRole action on the role’s database.
  • The userAdmin and userAdminAnyDatabase built-in roles provide createUser and grantRole actions on their respective resources.

MongoDB Create User Examples:

1. Create user with roles.

use r2schools

db.createUser({user:"r2admin", pwd:"r2admin@123", roles:[{role:"readWrite",db:"r2schools"},{role:"backup",db:"admin"}]})

MongoDB Create User

2. Create user without roles.

db.createUser({user:"r2test",pwd:"r2test",roles:[]})

3. To know the list of users in current database:

db.getUsers()

Output:

[ { "_id" : "r2schools.r2admin", "userId" : UUID("a68bb5cf-e10d-4259-b8af-95 922a63547c"), "user" : "r2admin", "db" : "r2schools", "roles" : [ { "role" : "readWrite", "db" : "r2schools" }, { "role" : "backup", "db" : "admin" } ], "mechanisms" : [ "SCRAM-SHA-1", "SCRAM-SHA-256" ] }, { "_id" : "r2schools.r2test", "userId" : UUID("b63629a0-8e6b-4da3-8302-7f 4ead965ae7"), "user" : "r2test", "db" : "r2schools", "roles" : [ ], "mechanisms" : [ "SCRAM-SHA-1", "SCRAM-SHA-256" ] } ]

4. If we want to see all users in entire MongoDB server, run the following command.

use admin db.system.users.find({},{_id:0,user:1})