Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run script against replica set in MongoDB

Tags:

mongodb

I have replica set of 3 nodes and I want to run a cleanup script against it every end of day. What I would do if there was only single node would be a simple bash script:

~/mongo/bin/mongo host:port cleanupScript.js

But since I want to run the same script against replica-set I can't use this approach. I would need to somehow find which node is primary and run the script against that node.

So the question: Is there a way how to run the script against whole replica set and let the mongo process pick the primary node and execute on it?

Thanks!

like image 942
Jan Zyka Avatar asked Oct 10 '12 13:10

Jan Zyka


People also ask

Which command can be used start a MongoDB process as part of a replica set?

On port 27017, it will launch a mongod instance with the name rs0. Connect to this mongod instance using the command prompt. To start a new replica set, use the Mongo client function rs. initiate().

Does MongoDB support replication?

MongoDB handles replication through a Replica Set, which consists of multiple MongoDB nodes that are grouped together as a unit. A Replica Set requires a minimum of three MongoDB nodes: One of the nodes will be considered the primary node that receives all the write operations.


1 Answers

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.

like image 88
Asya Kamsky Avatar answered Oct 03 '22 18:10

Asya Kamsky