Run script against replica set in MongoDB Run script against replica set in MongoDB mongodb mongodb

Run script against replica set in MongoDB


The mongo shell can connect directly to a replica set - this works with 2.4 (current), 2.2 (previous) and 2.0 (the version before that).

Assuming you have a replica set called myrs and your hosts are host1:27017 and host2:27017, use the following syntax:

mongo --host myrs/host1:27017,host2:27017

The shell will figure out the rest, including connecting to the primary and if the primary steps down or goes away it will reconnect to the new primary once it's elected.


Unfortunately, the 'mongo' shell does not support making connections to a replica set: only to individual nodes. You have two choices if you want to do this:

  • Use a different language, which supports making a connection to a replica set. (PHP, Python, Perl, Java and Ruby all support this.)
  • Have a driver script that runs an 'rs.status()' command, parses the output of that command, and determines the current primary. If it's not the node you've connected to, then re-connect to the correct primary node

I wish I had a better answer for you.


I normally set priority for a node in replicaset. This gives me freedom to chose which node should get read and write load.

In your case, I think, if you set priority for the nodes then you can always run your script against the highest priority node as that node will be primary almost all the time.

Setting priority is quite simple and straight forward. You can check this link http://docs.mongodb.org/manual/tutorial/force-member-to-be-primary/

I hope this will solve your problem.

OKAY.... Probably this is what you need..

#!/bin/bashPRIMARY=`~/mongo/bin/mongo localhost:27017 --eval "printjson(rs.isMaster())" | grep "primary" | cut -d"\"" -f4`echo "$PRIMARY"~/mongo/bin/mongo "$PRIMARY" cleanupScript.js

Run this on any node and it will give you the "server:port" of the primary. Give full path to the mongo executable.. just to avoid errors.

PS: the whole command is in the backticks. Somehow those are not visible so thought of telling you.