MongoDB连接报错UserNotFound:admin@automation用户不存在如何修复?
Hey there, let's figure out how to fix that UserNotFound error you're running into when connecting to MongoDB. The error message UserNotFound: Could not find user admin@automation tells us exactly what's going wrong—MongoDB is looking for a user named admin in the automation database, but that user doesn't exist there. Here's how to troubleshoot and fix this step by step:
1. Understand why this happens
MongoDB ties users to specific databases (called the authentication database). When you run mongo automation, you're connecting directly to the automation database, and when you pass -u admin, MongoDB assumes the admin user lives in that automation database. But your admin user is almost certainly created in the admin database (the default for superusers), not automation.
2. Fix the connection command
You need to tell MongoDB to use the admin database for authentication, even if you want to work with the automation database afterward. There are two easy ways to do this:
Option 1: Specify the authentication database in the command
Add the--authenticationDatabase adminflag to your original command:mongo automation --host machine40.scv.company.com -u admin -p passd --authenticationDatabase adminOption 2: Authenticate first in the admin database, then switch
Connect to theadmindatabase directly to authenticate, then switch toautomationonce you're logged in:mongo admin --host machine40.scv.company.com -u admin -p passd # Once logged in, run this to switch to your target database use automation
3. Verify the admin user exists
If the above commands still don't work, double-check that the admin user actually exists in the admin database. Log in with a user that has user management permissions, then run:
use admin db.getUser("admin")
If this returns null, the user doesn't exist. Create it with this command (make sure you're in the admin database):
use admin db.createUser( { user: "admin", pwd: "passd", roles: [ { role: "root", db: "admin" } ] # Grants full admin access } )
4. Double-check other connection details
- Make sure the hostname
machine40.scv.company.comis reachable from your machine (try pinging it or usingtelnetto check port 27017 is open). - If MongoDB is running on a non-default port, add the
--port <port-number>flag to your command. - Confirm you're using the correct password for the
adminuser.
内容的提问来源于stack exchange,提问作者Jeremyapple

