What does the error “not authorized on [database] to execute command” mean, and how can you resolve it?
The MongoDB error “not authorized on [database] to execute command” means that the authenticated user does not have the necessary permissions (roles) to run the specified command on the given database.
🔍 Why This Happens
MongoDB uses a Role-Based Access Control (RBAC) system. Each user is assigned roles that grant specific privileges on databases. This error typically occurs when:
-
The user is trying to read, write, or perform an administrative task on a database they don't have access to.
-
A script or application is attempting an operation (e.g.,
insert
,createIndex
,aggregate
) without the required privilege. -
The user is authenticated against the wrong database (especially common with external auth).
🛠️ How to Fix It
✅ 1. Check the User's Roles
Log in with an admin user and check the current user’s roles:
This will list all roles and databases the user has access to.
✅ 2. Grant the Appropriate Role
To grant access, use:
Common built-in roles include:
-
read
: Read-only access to a database -
readWrite
: Read/write access to a database -
dbAdmin
: Administrative tasks (like creating indexes) -
userAdmin
: Manage users and roles -
clusterAdmin
: Cluster-level operations
✅ 3. Authenticate on the Correct Database
Users are typically created in a specific database. If you're authenticating on the wrong one, access might fail:
Example (Mongo shell):
✅ 4. Check Your Application Connection String
Ensure the connection URI specifies the correct authentication database:
Or add:
Example:
✅ 5. Use a Role That Matches the Command
If you're trying to do something like create a collection, run an aggregation with $out
, or modify indexes, make sure the user has dbAdmin
or more advanced roles like dbOwner
.
✅ Example Fix Scenario
Error:
Fix:
Summary
-
The error means the user lacks permission for the attempted action.
-
Fix it by granting appropriate roles or correcting the authentication database.