[Python] 通过pymongo连接docker中开启了副本集的mongodb数据库

需要指定 directConnection=true&authSource=atp-test 参数,,否则会报连接副本集超时。

在 PyMongo 中,directConnection 参数可以决定客户端是否直接连接到 MongoDB 服务器,而不是自动发现所有的副本集成员。当 directConnection 设置为 true 时,客户端将只连接到 MongoDB 连接字符串中指定的服务器。
这个参数在某些情况下可能会有用,例如当你的应用无法访问副本集中的所有成员时。但请注意,当 directConnection 设置为 true 时,如果你指定的服务器不可用,客户端将无法自动切换到其他副本集成员。

在 MongoDB 中,authSource 参数用于指定进行身份验证的数据库。当你的用户在一个特定的数据库中创建,而你需要在另一个数据库中进行操作时,这个参数就会非常有用。
例如,假设你在 admin 数据库中创建了一个用户,但你需要使用这个用户来访问 atp-test 数据库。在这种情况下,你可以在连接字符串中设置 authSource=admin,这样 MongoDB 就会在 admin 数据库中验证用户的凭证,但实际的操作会在 test 数据库中进行。

from pymongo import MongoClient

# 创建一个 MongoClient 实例
client = MongoClient("mongodb://<username>:<password>@<host_ip>:<host_port>/?directConnection=true&authSource=atp-test")

# 选择一个数据库
db = client["test"]

# 选择一个集合
collection = db["execute_record"]

# 执行一个查询
documents = collection.find().limit(1000).skip(0)
print(documents)
for index in documents:
    print(index)

client.close()
posted @ 2024-08-14 17:06  夜歌乘年少  阅读(2)  评论(0编辑  收藏  举报