已知Mongo Shell同步操作,如何用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})
Option 2: Set Read Preference (Recommended for Modern Workflows)
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
replSetConfigureprivilege 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

