Implement custom role-based access control in MongoDB.
Instruction: Design a system within MongoDB to implement custom roles with specific permissions that go beyond the default roles provided.
Updated
Official answer
Start from an action/resource matrix and grant only required operations. For self-managed MongoDB, custom roles can be created through db.createRole by an appropriately authorized administrator. A role that spans databases must be created in admin; ordinary database roles cannot grant arbitrary cross-database privileges.
For a role that only reads sales.reports, this illustrative mongosh code makes both role and user database context explicit. It assumes the user already exists in appAuth:
const adminDb = db.getSiblingDB("admin");
adminDb.createRole({
role: "reportReader",
privileges: [{
resource: {db: "sales", collection: "reports"},
actions: ["find"]
}],
roles: []
});
db.getSiblingDB("appAuth").grantRolesToUser(
"reportService", [{role: "reportReader", db: "admin"}]
);
Test the application's actual operations using that service identity: reading the intended collection should succeed, while writes and unrelated reads should fail. Additional operations may need separately justified privileges. Inspect all inherited roles because permissions combine; a narrow role cannot cancel broader permissions granted elsewhere.
For Atlas, use its supported custom database-role management rather than assuming createRole is available. Keep role changes versioned, review access periodically and revoke obsolete grants. Collection privileges do not supply application row-level tenant authorization.