简体   繁体   English

通过 python 连接到 MongoDB

[英]Connect to MongoDB via python

I'm trying to connect to mongodb using python and code:我正在尝试使用 python 和代码连接到 mongodb:

myclient = pymongo.MongoClient("mongodb://root:password@mongo:27017/database_sample?authSource=admin")
db = myclient.database_sample
my_collection = db["database"]

but I'm getting但我得到

pymongo.errors.OperationFailure: Authentication failed., full error: {'ok': 0.0, 'errmsg': 'Authentication failed.', 'code': 18, 'codeName': 'AuthenticationFailed'}

Your question is not clear.你的问题不清楚。 I can suggest you a few things.我可以给你一些建议。 First be sure you are writing db name correctly.首先确保您正确编写数据库名称。 Second check if your password is valid.其次检查您的密码是否有效。 If not try to change the connection path in MongoClient since this function is client only.如果不尝试更改 MongoClient 中的连接路径,因为此功能仅限客户端。

Your code is correct;您的代码是正确的; Authentication failed means that at least one of your username , password or authSource is incorrect for the current database .身份验证失败意味着您的usernamepasswordauthSource中的至少一个对于当前数据库不正确。 If you have special characters in your password, that could be an issue.如果您的密码中有特殊字符,那可能是个问题。

At the command prompt on the same machine you are running the python code , run:您正在运行 python 代码的同一台机器上的命令提示符处,运行:

mongo 'mongodb://root:password@mongo:27017/database_sample?authSource=admin'

In most circumstances this will exhibit the same behaviour as connecting via python / pymongo.在大多数情况下,这将表现出与通过 python / pymongo 连接相同的行为。

Permissions are set at a database level, so it could be your username/password works in certain databases but not others.权限是在数据库级别设置的,因此它可能是您的用户名/密码在某些数据库中有效,但在其他数据库中无效。 so at the command prompt again it's also worth trying:所以再次在命令提示符下也值得一试:

mongo 'mongodb://root:password@mongo:27017/admin?authSource=admin'

and seeing if that connects or exhibits some different behaviour.并查看它是否连接或表现出一些不同的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM