Python连接访问mongodb副本集
代码如下:
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}
补充说明:如果副本集只剩下一个节点是无法访问的