无法使用 PyMongo 连接 Atlas 集群

Posted

技术标签:

【中文标题】无法使用 PyMongo 连接 Atlas 集群【英文标题】:Unable to connect with Atlas cluster using PyMongo 【发布时间】:2021-08-18 06:28:36 【问题描述】:

一段时间以来,我一直在尝试让 Pymongo 与我的免费 atlas 集群一起工作,但只是遇到如下错误:

    raise ServerSelectionTimeoutError(
    pymongo.errors.ServerSelectionTimeoutError: connection closed,connection closed,connection closed, Timeout: 30s, Topology Description: <TopologyDescription id: 60b3d56c099a114d04aa3b66, topology_type: ReplicaSetNoPrimary, servers: [<ServerDescription ('sandbox-shard-00-00.r2jpi.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('connection closed')>, <ServerDescription ('sandbox-shard-00-01.r2jpi.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('connection closed')>, <ServerDescription ('sandbox-shard-00-02.r2jpi.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('connection closed')>]>
    I am not sure what is causing this. Yes, my IP is whitelisted, and yes my Atlas database has a user with proper privileges. All the functions which involve communicating with the server seems to be failing.

如果我只是跑步:

import pymongo
from pymongo import MongoClient
import datetime

client = MongoClient(
    'mongodb://<username>:<pw>@sandbox.r2jpi.mongodb.net/test?authSource=admin&replicaSet=atlas-jexqkj-shard-0&readPreference=primary&appname=MongoDB%20Compass&ssl=true')
db = client.sample_mflix
print(db)

我明白了:

Database(MongoClient(host=['sandbox-shard-00-02.r2jpi.mongodb.net:27017', 'sandbox-shard-00-00.r2jpi.mongodb.net:27017', 'sandbox-shard-00-01.r2jpi.mongodb.net:27017'], document_class=dict, tz_aware=False, connect=True, retrywrites=True, w='majority', authsource='admin', replicaset='atlas-jexqkj-shard-0', ssl=True), 'sample_mflix')

操作系统:Windows 10

Python 版本:3.9.2

PyMongo 版本:3.9.0

下面是我尝试运行的代码(导致 serverTimeOutError)

import pymongo
from pymongo import MongoClient
import datetime

client = MongoClient(
    'mongodb://<username>:<pw>@sandbox.r2jpi.mongodb.net/test?authSource=admin&replicaSet=atlas-jexqkj-shard-0&readPreference=primary&appname=MongoDB%20Compass&ssl=true')

db = client.sample_mflix
trying = db.trying

personDocument = 
    "name": "first": "Alan", "last": "Turing",
    "birth": datetime.datetime(1912, 6, 23),
    "death": datetime.datetime(1954, 6, 7),
    "contribs": ["Turing machine", "Turing test", "Turingery"],
    "views": 1250000

trying.insert_one(personDocument)

【问题讨论】:

【参考方案1】:

Atlas 集群使用 SRV 记录来确定每个分片/副本集的 DNS 记录。

因此,您需要使用以mongodb+srv:// 开头的连接字符串进行连接。

【讨论】:

以上是关于无法使用 PyMongo 连接 Atlas 集群的主要内容,如果未能解决你的问题,请参考以下文章

MongoError:在 mongoDB atlas 中首次连接时无法连接服务

MongoError:在 mongoDB atlas 中首次连接时无法连接服务

Lumen连接MongoDB Atlas时认证失败

连接后 mongobee 在 Atlas 集群上读取 DBname.system.indexes 失败

如何将atlas mongodb与集群连接

使用 Mongoose 和 SRV 连接字符串将数据插入 MongoDB Atlas