Skip to content
not authorized on admin to execute command

not authorized on admin to execute command

DodaTech 2 min read

The MongoDB error “not authorized on admin to execute command” means your authenticated user does not have the required privileges to run the command you attempted on the specified database.

What It Means

MongoDB’s role-based access control evaluated your user’s roles against the command’s required privileges and found them insufficient. Even though you are authenticated, your user lacks the action on the resource for the attempted operation.

Why It Happens

  • The user has read role but attempts a write operation.
  • The user has access to one database but the command targets admin or a different database.
  • The user was granted a role scoped to a specific collection but the command runs on the entire database.
  • Commands like dbStats, listCollections, or createIndex require cluster-level or database-specific privileges.
  • The user was created before roles were properly assigned.

How to Fix It

1. Check current user roles

mongosh -u youruser -p
db.runCommand({ connectionStatus: 1 })

2. Grant the required role

Connect as a user with userAdminAnyDatabase or root:

mongosh admin -u admin -p
db.grantRolesToUser('youruser', [
  { role: 'readWrite', db: 'mydb' },
  { role: 'dbAdmin', db: 'mydb' }
])

3. Grant cluster-level privileges if needed

db.grantRolesToUser('youruser', [
  { role: 'clusterMonitor', db: 'admin' }
])

4. Use a predefined role or create a custom one

MongoDB provides built-in roles: read, readWrite, dbAdmin, userAdmin, dbOwner, clusterMonitor, backup, restore, and root.

5. Reconnect with the correct database scope

mongosh mydb -u youruser -p

FAQ

What is the difference between 'read' and 'readWrite' roles?
read allows reading documents in all non-system collections. readWrite includes read plus insert, update, delete, and index creation for the specified database.
How do I give a user access to all databases?
Grant the readAnyDatabase, readWriteAnyDatabase, or userAdminAnyDatabase roles from the admin database. Only use these for administrative users, not application users.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro