【问题标题】:Problems with connect to MongoDB Atlas from Python从 Python 连接到 MongoDB Atlas 的问题
【发布时间】:2022-02-05 17:21:18
【问题描述】:

我是 MongoDB Atlas 和 Python 的新手。我正在使用 Python 3.9 和 PyMongo 4.0.1:我无法连接到基于 MongoDB 指令创建的免费 MongoDB Atlas 集群。请看附图——https://behainguyen.files.wordpress.com/2022/01/cloud-mongo-db-connection-string.jpg,我的连接字符串是:

mongodb+srv://behai:<password>@cluster0.71o6u.mongodb.net/myFirstDatabase?retryWrites=true&w=majority

我已替换为 MongoDB Atlas 中用户“behai”的密码。我将它作为 MONGO_CONNECTION_STRING 存储在我的 keys.py 文件中。

我连接为:

import pymongo
import keys

client = pymongo.MongoClient( keys.MONGO_CONNECTION_STRING )

我有错误:

ConfigurationError: All nameservers failed to answer the query cluster0.71o6u.mongodb.net. IN TXT: Server 192.168.0.1 UDP port 53 answered DNS message is malformed.

如果我从连接字符串中删除了“+srv”,我可以连接,但是以后的访问(例如创建数据库、创建集合然后插入到集合中)会导致错误:

ServerSelectionTimeoutError: cluster0.71o6u.mongodb.net:27017: [Errno 11001] getaddrinfo failed, Timeout: 30s, Topology Description: <TopologyDescription id: 61d8d475109bbda8e8b938f0, topology_type: Unknown, servers: [<ServerDescription ('cluster0.71o6u.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('cluster0.71o6u.mongodb.net:27017: [Errno 11001] getaddrinfo failed')>]>

当我尝试 ping cluster0.71o6u.mongodb.net 时:

C:\>ping cluster0.71o6u.mongodb.net

我会收到这样的回复:

Ping request could not find host cluster0.71o6u.mongodb.net. Please check the name and try again.

主机“cluster0.71o6u.mongodb.net”好像不存在?

但是当我查看我的 MongoDB Atlas 窗口时,我可以看到我在过去 99 小时内建立了 6 个连接。

【问题讨论】:

    标签: python mongodb pymongo


    【解决方案1】:

    尝试使用 pip 安装 dnspython/pymongo[srv]

    import pymongo
        
    db = pymongo.MongoClient("mongodb+srv://behai:<password>@cluster0.71o6u.mongodb.net/myFirstDatabase?retryWrites=true&w=majority")
    

    【讨论】:

    • 我执行了你的建议:``` 在 [9] 中:pip install pymongo[srv] 要求已经满足:pymongo[srv] in c:\users\behai\anaconda3\lib\site-包 (4.0.1) 已满足要求:c:\users\behai\anaconda3\lib\site-packages 中的 dnspython=1.16.0 (来自 pymongo[srv]) (2.1.0) 注意:您可能需要重新启动内核才能使用更新的软件包。 ```尽管如此,我还是继续运行代码,但仍然有错误。谢谢你的帮助。我很感激你的好意。
    【解决方案2】:

    如果您使用 Pycharm,请设置 Project:YOURPROJECT 并检查 dnspython 是否存在,如果不存在则单击 + 图标并搜索 dnspython 并安装它。

    当我尝试在命令行上安装时,它一直说它已经安装但没有工作。这可能会解决您的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-07
      • 1970-01-01
      • 1970-01-01
      • 2021-01-04
      • 2021-02-01
      • 2020-08-11
      • 1970-01-01
      • 2018-10-26
      相关资源
      最近更新 更多