Skip to content

Instantly share code, notes, and snippets.

@phillco
Created July 5, 2012 20:22
Show Gist options
  • Save phillco/3056217 to your computer and use it in GitHub Desktop.
Save phillco/3056217 to your computer and use it in GitHub Desktop.
Replica set step down example
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MongoDB.Driver;
using MongoDB.Bson;
namespace MongoStepDown
{
class Program
{
static void Main( string[] args )
{
// Get the address of the primary server.
string address = GetAddressOfPrimary( );
// Connect to it.
Console.WriteLine( "Connecting to " + address + "..." );
var mongo = MongoServer.Create( "mongodb://" + address + "/" );
// Make it step down.
var result = mongo["admin"].RunCommand( "replSetStepDown" );
Console.WriteLine( "Result: " + result );
}
static string GetAddressOfPrimary( )
{
// Connect to the first localhost server.
var server = new MongoServer( new MongoServerSettings { Server = new MongoServerAddress( "localhost" ), SlaveOk = true } );
// Get the replica set members.
var status = server["admin"].RunCommand( "replSetGetStatus" );
var members = status.Response["members"].AsBsonArray;
// Find the primary.
foreach ( BsonDocument member in members )
{
if ( member["stateStr"] == "PRIMARY" )
return member["name"].AsString;
}
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment