MongoDB Authentication — Creating users and assigning rules.

Rishabh Sharma
2 min readFeb 27, 2022

MongoDB is of the most popular databases. It is cross-platform ,easily scalable and gives high performance. It is NoSQL database and works on the concept of collection and document.

In MongoDB we can create users which can have specified roles. It provides authentication, authorization, and abstraction. Only the user which have privileges can perform that task.

DB admin vs DB owner

The database owner is the operating system user that created the database. The database administrator (DBA) is an individual that has been granted administrator rights within the database.

MongoDb user roles

read-Provides the ability to read data on all non-system collections

readWrite- all the privileges of read with additional ability to write on non system collections.

DB administration rules –

dbAdmin — Grant privileges to perform administrative tasks

userAdmin — Allows you to create and modify users and roles on the current database

dbOwner — This role combines the following:

  • readWrite
  • dbAdmin
  • userAdmin

In this we are using MongoDB inside a docker container. To know how to set it up go here .

First of all to view all the collections present use following command-

show dbs
show dbs to show collections.

Here I dont have any collections so i made a collection using-

db.createCollection(NameOfCollection)
Creating a Collection

Now navigate to the to collection for which you need to add user and assign rules , it can be done using -

use NameofCollection
Switching to the DB

Use the following command to add user and define the rules

db.createUser({
user: "testUser",
pwd: "testPass",
roles: ["readWrite","dbAdmin"]
});

Here we have given “readWrite” and “dbAdmin” role to user named “testUser” with password “testPass”.

User Created with roles.

You can create more users and assign the rules in a similar way.

Thanks for reading. Hope it was helpful.

--

--