Nov 212013
 

When configuring the attributes of members of a Mongo DB replica set, either in the mongo shell or a script, the typical procedure is to set each attribute by its array reference. The weakness in this method is that it’s necessary to know what the array index is of the host whose attribute you need to configure. This may not be possible for a generalized script.

cfg = rs.config();
cfg.members[1].priority = 2;
rs.reconfig(cfg);

However, with a bit of mongo javascript it’s possible to write a small function to cycle through the member config array, determine the index of a host and then set an attribute.

In this example, we want to configure the Mongo DB nodedb02.example.com as a hidden node. This can be done like this:

cfg = rs.config();
cfg.members.forEach( 
	function(item, i) {
		if ( item.host == "nodedb02.example.com" ) 
		{ 
			cfg.members[i].priority = 0;
			cfg.members[i].hidden = true;
			rs.reconfig(cfg);
		}  
	} 
)

If, on the other hand, you wanted to change the slave delay on a read-only reporting node, this could be accomplished by testing each node to find which has the “hidden” attribute set to “true”:

		if ( item.hidden == "true" ) 
		{ 
			cfg.members[i].slaveDelay=0
			rs.reconfig(cfg)
		}  

Use this function in Mongo JS scripts, be it with Capistrano, Puppet or some other automation technique, and everything got just a bit more hands-off.


Matt Parsons is a freelance Linux specialist who has designed, built and supported Unix and Linux systems in the finance, telecommunications and media industries.

He lives and works in London.