0
0
MongoDBquery~5 mins

Built-in roles (read, readWrite, dbAdmin) in MongoDB

Choose your learning style9 modes available
Introduction

Built-in roles help control what users can do in a MongoDB database. They make it easy to give the right access without confusion.

When you want someone to only look at data without changing it.
When a user needs to add, update, or delete data in the database.
When a user should manage database settings but not change data.
When you want to quickly assign common permissions without creating custom roles.
Syntax
MongoDB
db.createUser({
  user: "username",
  pwd: "password",
  roles: ["roleName"]
})
Replace "username" and "password" with the user's login details.
Replace "roleName" with one of the built-in roles like "read", "readWrite", or "dbAdmin".
Examples
This user can only read data from the database.
MongoDB
db.createUser({
  user: "reader",
  pwd: "pass123",
  roles: ["read"]
})
This user can read and write data (add, update, delete).
MongoDB
db.createUser({
  user: "writer",
  pwd: "pass123",
  roles: ["readWrite"]
})
This user can manage database settings but cannot change data.
MongoDB
db.createUser({
  user: "adminUser",
  pwd: "pass123",
  roles: ["dbAdmin"]
})
Sample Program

This example creates a user with readWrite access on the exampleDB database. Then, the user can add a product to the products collection and read it back.

MongoDB
use exampleDB

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

// Then login as testUser and insert a document
// mongo -u testUser -p testPass --authenticationDatabase exampleDB
// use exampleDB
// db.products.insertOne({name: "apple", price: 1.2})

// To check the inserted document
// db.products.find()
OutputSuccess
Important Notes

Built-in roles cover most common needs, so you usually don't need to create custom roles.

Always assign the least privilege needed to keep your data safe.

Roles apply per database, so a user can have different roles on different databases.

Summary

Built-in roles control user permissions easily.

Use read to allow only viewing data.

Use readWrite to allow viewing and changing data.

Use dbAdmin to allow managing database settings.