0
0
MongodbHow-ToBeginner · 4 min read

How to Create User in MongoDB: Step-by-Step Guide

To create a user in MongoDB, use the db.createUser() method in the Mongo shell. Specify the username, password, and roles to grant the user appropriate permissions.
📐

Syntax

The db.createUser() method creates a new user in the current database. You must provide a user name, pwd (password), and roles array that defines the user's permissions.

  • user: The username as a string.
  • pwd: The password as a string.
  • roles: An array of role objects or role names that specify the user's access rights.
mongodb
db.createUser({
  user: "username",
  pwd: "password",
  roles: [ { role: "readWrite", db: "databaseName" } ]
})
💻

Example

This example creates a user named appUser with password securePass123 who has read and write access to the myAppDB database.

mongodb
use myAppDB

db.createUser({
  user: "appUser",
  pwd: "securePass123",
  roles: [ { role: "readWrite", db: "myAppDB" } ]
})
Output
{ "ok" : 1 }
⚠️

Common Pitfalls

Common mistakes when creating users in MongoDB include:

  • Not switching to the correct database before creating the user, which causes the user to be created in the wrong database.
  • Using weak or empty passwords, which compromises security.
  • Assigning incorrect or insufficient roles, leading to permission errors.
  • Trying to create a user without enabling authentication in MongoDB configuration.

Always ensure you are in the right database and assign roles carefully.

mongodb
/* Wrong: Creating user in wrong database */
use admin

db.createUser({
  user: "appUser",
  pwd: "pass",
  roles: [ { role: "readWrite", db: "admin" } ]
})

/* Right: Specify database and roles explicitly */
use myAppDB

db.createUser({
  user: "appUser",
  pwd: "strongPassword",
  roles: [ { role: "readWrite", db: "myAppDB" } ]
})
📊

Quick Reference

ParameterDescriptionExample
userUsername as a string"appUser"
pwdPassword as a string"securePass123"
rolesArray of roles with database context[{ role: "readWrite", db: "myAppDB" }]
db.createUser()Method to create user in current databasedb.createUser({...})

Key Takeaways

Always use db.createUser() in the correct database context to create a user.
Specify strong passwords and appropriate roles for security and access control.
Switch to the target database before creating the user to avoid confusion.
Roles define what actions the user can perform; choose them carefully.
MongoDB authentication must be enabled to enforce user access control.