MongoDB Create User

By Yashwant Chavan, Views 2454, Last updated on 01-Mar-2019

In this tutorial we will learn how to creates a new user for the database using db.createUser() method and provide the respected user roles.

tags mongodb

mongoDB Create User - db.createUser()

Creates a new database user. db.createUser() method returns a duplicate user error, if the user already exists on the database.

db.createUser(user, writeConcern)

user - document contains the user authentication and access information of the user.

writeConcern - Optional document parameter , Introduce in version 2.6. It describe level of acknowledgement requested from MongoDB while performing write / create operations to a standalone mongoDB, replica sets, sharded clusters.

user document syntax

user - String type parameter, name of the new user which you want to create.

pwd - String type parameter, The user’s password.

customData - document type optional parameter, Any arbitrary information about user like user full name , employee id or department etc.

roles - array type parameter, which helps to specify the user roles. You can specify built-in roles or user-defined roles. If you don't want to specify user roles then pass an empty array [] to create users method.

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

db.createUser() Example

In below example we will create the new user ("scott") for the database "technicalkeeda" along with its password credentials, custom data information and respected roles.

> use technicalkeeda
switched to db technicalkeeda

> db.createUser(
 {
  user: "scott",
  pwd: "tiger",
  customData: { employeeId: 999, employeeName: "Yashwant Chavan" , dept: "Information Technology"  },
  roles: [ "readWrite", "dbAdmin" ]
 },
 { w: "majority" , wtimeout: 5000 }
)

Successfully added user: {
        "user" : "scott",
        "customData" : {
                "employeeId" : 999,
                "employeeName" : "Yashwant Chavan",
                "dept" : "Information Technology"
        },
        "roles" : [
                "readWrite",
                "dbAdmin"
        ]
}
>
Yashwant

Yashwant

Hi there! I am founder of technicalkeeda.com and programming enthusiast. My skills includes Java,J2EE, Spring Framework, Nodejs, PHP and lot more. If you have any idea that you would want me to develop? Lets connect: yashwantchavan[at][gmail.com]