使用PyMongo实现MongoDB数据库复制的步骤

2023年 8月 12日 47.4k 0

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)

  • 在主服务器上创建一个MongoDB副本集。
  • 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配置文件加入MongoDB副本集。
  • 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)

  • 现在,主服务器上的数据库和集合将被复制到副本服务器上。您可以在两个服务器上使用find()方法来检查是否存在数据。
  • 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)

    相关文章

    Oracle如何使用授予和撤销权限的语法和示例
    Awesome Project: 探索 MatrixOrigin 云原生分布式数据库
    下载丨66页PDF,云和恩墨技术通讯(2024年7月刊)
    社区版oceanbase安装
    Oracle 导出CSV工具-sqluldr2
    ETL数据集成丨快速将MySQL数据迁移至Doris数据库

    发布评论