0
0
MongoDBquery~5 mins

Creating users and roles in MongoDB

Choose your learning style9 modes available
Introduction
Creating users and roles helps control who can access your database and what they can do. It keeps your data safe and organized.
When you want to give someone permission to read data but not change it.
When you need to allow a user to add or update data in the database.
When you want to create a special role for a group of users with specific permissions.
When you want to restrict access to certain parts of your database.
When setting up a new database and need to secure it from unauthorized access.
Syntax
MongoDB
db.createUser({
  user: "username",
  pwd: "password",
  roles: [
    { role: "roleName", db: "databaseName" }
  ]
})

// To create a role:
db.createRole({
  role: "roleName",
  privileges: [
    {
      resource: { db: "databaseName", collection: "collectionName" },
      actions: ["action1", "action2"]
    }
  ],
  roles: []
})
Use db.createUser() to add a new user with specific roles.
Use db.createRole() to define a custom role with specific privileges.
Examples
Creates a user who can only read data from 'myDatabase'.
MongoDB
db.createUser({
  user: "readerUser",
  pwd: "readerPass",
  roles: [ { role: "read", db: "myDatabase" } ]
})
Creates a user with administrative rights on 'myDatabase'.
MongoDB
db.createUser({
  user: "adminUser",
  pwd: "adminPass",
  roles: [ { role: "dbAdmin", db: "myDatabase" } ]
})
Creates a custom role that allows reading and writing on 'myCollection' in 'myDatabase'.
MongoDB
db.createRole({
  role: "customReadWrite",
  privileges: [
    {
      resource: { db: "myDatabase", collection: "myCollection" },
      actions: ["find", "insert", "update"]
    }
  ],
  roles: []
})
Sample Program
This creates a role 'limitedEditor' that can read and update the 'products' collection. Then it creates a user 'editorUser' with that role.
MongoDB
use myDatabase

db.createRole({
  role: "limitedEditor",
  privileges: [
    {
      resource: { db: "myDatabase", collection: "products" },
      actions: ["find", "update"]
    }
  ],
  roles: []
})

db.createUser({
  user: "editorUser",
  pwd: "editorPass",
  roles: [ { role: "limitedEditor", db: "myDatabase" } ]
})
OutputSuccess
Important Notes
Always use strong passwords for users to keep your database secure.
Roles can include other roles to combine permissions easily.
You must have admin rights to create users and roles.
Summary
Creating users controls who can access your database.
Roles define what actions users can perform.
You can create custom roles for specific permissions.