MongoDB数据库复制可以通过使用PyMongo的replSetInitiate()方法和replSetReconfig()方法来实现。下面是详细的步骤:
在两个MongoDB服务器上安装并启动MongoDB服务。
在主服务器上创建一个要复制的数据库,并在其中创建一些集合和文档用于测试。
import pymongo
client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["pidancode"]
collection = db["test"]
document = {"name": "pidancode.com", "category": "education"}
collection.insert_one(document)
config = {
"_id": "rs0",
"members": [
{"_id": 0, "host": "localhost:27017"},
{"_id": 1, "host": "localhost:27018"},
{"_id": 2, "host": "localhost:27019"}
]
}
admin_db = client["admin"]
result = admin_db.command("replSetInitiate", config)
print(result)
config = {
"_id": "rs0",
"members": [
{"_id": 0, "host": "localhost:27017"},
{"_id": 1, "host": "localhost:27018"},
{"_id": 2, "host": "localhost:27019"}
]
}
admin_db = client["admin"]
result = admin_db.command("replSetReconfig", config)
print(result)
db = client["pidancode"]
collection = db["test"]
print("Data in primary server:")
for document in collection.find():
print(document)
client = pymongo.MongoClient("mongodb://localhost:27019/")
db = client["pidancode"]
collection = db["test"]
print("Data in secondary server:")
for document in collection.find():
print(document)