Custom roles let you control exactly what actions users can do in your database. This helps keep your data safe and organized.
0
0
Custom role creation in MongoDB
Introduction
You want to give a user permission to read data but not change it.
You need a user to manage only certain collections, not the whole database.
You want to limit a user's ability to create or delete data.
You want to create a role for a specific job, like reporting or backups.
You want to follow security rules by giving minimum needed access.
Syntax
MongoDB
db.createRole({
role: "roleName",
privileges: [
{
resource: { db: "databaseName", collection: "collectionName" },
actions: ["action1", "action2"]
}
],
roles: []
})role: The name of your new role.
privileges: What the role can do and where.
Examples
This role lets users only read data from the 'orders' collection in the 'sales' database.
MongoDB
db.createRole({
role: "readOnly",
privileges: [
{
resource: { db: "sales", collection: "orders" },
actions: ["find"]
}
],
roles: []
})This role allows full control over the 'orders' collection.
MongoDB
db.createRole({
role: "orderManager",
privileges: [
{
resource: { db: "sales", collection: "orders" },
actions: ["find", "insert", "update", "remove"]
}
],
roles: []
})This role allows the user to read data from all collections in all databases.
MongoDB
db.createRole({
role: "backupRole",
privileges: [
{
resource: { db: "", collection: "" },
actions: ["find"]
}
],
roles: []
})Sample Program
This creates a role named 'reportViewer' that can only read data from the 'reports' collection in the 'companyDB' database.
MongoDB
db.createRole({
role: "reportViewer",
privileges: [
{
resource: { db: "companyDB", collection: "reports" },
actions: ["find"]
}
],
roles: []
})OutputSuccess
Important Notes
You must have the 'userAdmin' or 'userAdminAnyDatabase' role to create custom roles.
Use specific actions like 'find', 'insert', 'update', 'remove' to control permissions.
Roles can include other roles by listing them in the 'roles' array for easier management.
Summary
Custom roles let you give users only the permissions they need.
You define roles by naming them and listing what actions they can do on which data.
Creating roles helps keep your database secure and organized.