gpt4 book ai didi

python - 使用pymongo无需密码连接到MongoDB

转载 作者:行者123 更新时间:2023-12-05 03:29:26 31 4
gpt4 key购买 nike

我对 pymongo 和 MongoDB 的问题有点困惑。

我有一个 MongoDB 服务器,我可以使用 Studio 3T 连接它而无需任何密码(在 VPN 后面): enter image description here enter image description here

mongodb://mongodb-dev.my.server:27017/?serverSelectionTimeoutMS=5000&connectTimeoutMS=10000

当我从 Python 连接到服务器时出现错误:

pymongo.errors.ServerSelectionTimeoutError: Could not reach any servers in [('mongodb-dev', 27017)]. Replica set is configured with internal hostnames or IPs?, Timeout: 5.0s, Topology Description: <TopologyDescription id: 6200d97072f39326314e6916, topology_type: ReplicaSetNoPrimary, servers: [<ServerDescription ('mongodb-dev', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('mongodb-dev:27017: [Errno 11001] getaddrinfo failed

Python 脚本:

import pymongo

client = pymongo.MongoClient('mongodb://mongodb-dev.my.server:27017/?serverSelectionTimeoutMS=5000&connectTimeoutMS=10000')

db = client.get_database('feeeper')
col = db.get_collection('my_collection')

cur = col.find({}, {'body': 1})
last_task = cur.sort([('created', pymongo.DESCENDING)]).limit(1)

for t in last_task:
print(t)

更新:Ping 到服务器工作正常: enter image description here

我可以使用 mongo shell 连接到服务器: enter image description here

最佳答案

问题在于 MongoClinet 构造函数的默认参数。构造函数的参数 directConnection 具有默认值 False — 连接到副本集:

directConnection (optional): if True, forces this client toconnect directly to the specified MongoDB host as a standalone. If false, the client connects to the entire replica set of which the given MongoDB host(s) is a part. If this is True and a mongodb+srv:// URI or a URI containing multiple seeds is provided, an exception will be raised.

当我将 directConnection 设置为 True 时,查询工作正常。

关于python - 使用pymongo无需密码连接到MongoDB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71015606/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com