MongoDB副本集详解与实战操作
from pymongo import MongoClient
# 连接到MongoDB副本集
def connect_to_replica_set(replica_set_members):
client = MongoClient(replica_set_members, replicaSet='rs0')
return client.admin
# 初始化副本集配置
def initiate_replica_set(admin):
config = {
"_id": "rs0",
"members": [
{"_id": 0, "host": "mongodb0.example.net:27017"},
{"_id": 1, "host": "mongodb1.example.net:27017"},
{"_id": 2, "host": "mongodb2.example.net:27017", "arbiterOnly": True},
]
}
admin.command('replSetInitiate', config)
# 连接到副本集并初始化
admin = connect_to_replica_set(['mongodb0.example.net:27017', 'mongodb1.example.net:27017', 'mongodb2.example.net:27017'])
initiate_replica_set(admin)
print("副本集初始化成功")
这段代码使用了pymongo
库来连接MongoDB副本集并初始化副本集配置。首先定义了连接函数connect_to_replica_set
,它接收副本集成员列表并返回管理员连接。然后定义了初始化函数initiate_replica_set
,它接收管理员连接作为参数并执行初始化命令。最后,连接到副本集并初始化配置。
评论已关闭