You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

已知Mongo Shell同步操作,如何用PyMongo实现主从节点同步?

How to Replicate MongoDB Shell Sync Operations with PyMongo

Hey there! Converting those MongoDB Shell commands to PyMongo is straightforward once you know the equivalent methods. Let's walk through each step with clear code examples:

1. Connect to the Secondary Node

First, establish a connection to the replica set secondary node you want to configure—this replaces the mongo --host <host>:<port> shell command:

from pymongo import MongoClient

# Replace <host> and <port> with your secondary node's actual details
secondary_client = MongoClient("<host>:<port>")

2. Allow Reads from the Secondary (Equivalent to rs.slaveOk())

In the shell, rs.slaveOk() enables read operations on the secondary. With PyMongo, you have two reliable approaches:

Option 1: Mirror the Shell Command Directly

Use the setSlaveOk admin command to replicate exactly what rs.slaveOk() does:

# Execute the command on the admin database
secondary_client.admin.command({"setSlaveOk": 1})

A more robust way is to define the read preference when creating the client, which ensures all subsequent reads target secondary nodes by default:

from pymongo.read_preferences import ReadPreference

secondary_client = MongoClient(
    "<host>:<port>",
    read_preference=ReadPreference.SECONDARY
)

3. Force Sync from a Specific Node (Equivalent to rs.syncFrom("<host>:<port>"))

To tell the secondary to sync from a specific primary or peer node (instead of letting the replica set auto-select), use the replSetSyncFrom admin command via PyMongo:

# Replace <target_host>:<target_port> with the node you want to sync from
secondary_client.admin.command({"replSetSyncFrom": "<target_host>:<target_port>"})

Quick Notes to Keep in Mind

  • Permissions: Your MongoDB user needs the replSetConfigure privilege to run these replica set commands.
  • Replica Set Requirement: These operations only work if the node is part of a MongoDB replica set—standalone nodes won't recognize replica set-specific commands.
  • Verify Sync Status: You can check if the sync is working by running secondary_client.admin.command("replSetGetStatus") and inspecting the output for sync details.

内容的提问来源于stack exchange,提问作者DominikB1

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:36:18