Python連線訪問mongodb副本集

lucky_tomato發表於2024-05-01

程式碼如下:

from pymongo import MongoClient
 
# 配置副本集的地址
replica_set_hosts = [
    "192.168.10.135:27017",
    "192.168.10.136:27018",
    "192.168.10.137:27019"
]
 
# 建立MongoClient連線
client = MongoClient(replica_set_hosts, username="admin", password="123456", authSource="admin",connecttimeoutms=5,serverSelectionTimeoutMS=5)
 
# 連線到資料庫和集合
database = client["test2"]
collection = database["c3"]
 
# 進行查詢操作
documents = collection.find({})
for document in documents:
    print(document)

返回結果

{'_id': ObjectId('662d243bb772dcca3598ddf2'), 'uname': 'zs2', 'age': 2.0}
{'_id': ObjectId('662d243bb772dcca3598ddf3'), 'uname': 'zs3', 'age': 3.0}
{'_id': ObjectId('662d243bb772dcca3598ddf1'), 'uname': 'zs1', 'age': 1.0}
{'_id': ObjectId('662d243bb772dcca3598ddf4'), 'uname': 'zs4', 'age': 4.0}
{'_id': ObjectId('662d243bb772dcca3598ddf5'), 'uname': 'zs5', 'age': 5.0}
{'_id': ObjectId('662d243bb772dcca3598ddf6'), 'uname': 'zs6', 'age': 6.0}
{'_id': ObjectId('662d243bb772dcca3598ddf7'), 'uname': 'zs7', 'age': 7.0}
{'_id': ObjectId('662d243bb772dcca3598ddf8'), 'uname': 'zs8', 'age': 8.0}
{'_id': ObjectId('662d243bb772dcca3598ddf9'), 'uname': 'zs9', 'age': 9.0}
{'_id': ObjectId('662d243bb772dcca3598ddfa'), 'uname': 'zs10', 'age': 10.0}
{'_id': ObjectId('663259d31f00f220c3d2dcd1'), 'uname': 'test01', 'age': 11.0}

補充說明:如果副本集只剩下一個節點是無法訪問的  

  

相關文章