grantRolesToUser (Grant Roles)
Last updated: 2026-10-09
grantRolesToUser (Grant Roles)
grantRolesToUser appends roles to an existing user — incremental, keeping all current roles (unlike updateUser's wholesale replacement). In mongosh call db.grantRolesToUser(user, roles). Common built-in roles can be plain strings; cross-database roles use { role, db } objects. Requires userAdmin or root.
| Category | User Authentication |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
db.grantRolesToUser("<username>", [ { role: "read", db: "shop" } ])
⚙️ Parameters
| roles | Roles to add; appended, not replacing |
|---|
Returns:Returns { ok: 1 } on success
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// grantRolesToUser: add a read role
use admin
db.grantRolesToUser('reader', [
{ role: 'read', db: 'analytics' }
])
Output:
{ ok: 1 }
📌 Notes
- Granting is additive — existing roles stay
- Unknown roles or insufficient privileges error out
- Use strings for built-in roles, { role, db } objects cross-db
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QGrant via grantRolesToUser vs updateUser?
AgrantRolesToUser appends; updateUser replaces the role list.
QCan I grant custom roles?
AYes — after creating them with createRole.
QWhat privileges does this need?
AuserAdmin or root.