Blake Mitchell
Blake Mitchell

Reputation: 2787

Test if MongoDB server is part of a replica set at run time

I have the same software deployed in multiple environments, some use a MongoDB replica set, and some use a single server. There are certain update operations where I use WriteConcern.WMajority, but this throws an exception if the server is not part of a replica set.

I'm looking for a way to ask the server if it is part of a replica set, so I will know if it is safe to use WriteConcern.WMajority. My attempt was this:

string connStr = System.Configuration.ConfigurationManager
    .ConnectionStrings["connStrName"].ConnectionString;
var server = new MongoDB.Driver.MongoClient(connStr).GetServer();
bool isReplicaSet = server.GetDatabase("admin")
    .RunCommand("replSetGetStatus").Ok;

But this throws MongoDB.Driver.MongoCommandException: Command 'replSetGetStatus' failed: not running with --replSet (response: { "ok" : 0.0, "errmsg" : "not running with --replSet" }). Is catching this exception my best option?

Upvotes: 1

Views: 1221

Answers (1)

Reda
Reda

Reputation: 2289

public bool IsPartOfReplicaSet(string connectionString)
{
    var result = new MongoClient(connectionString)
        .GetServer()
        .GetDatabase("admin")
        .RunCommand("getCmdLineOpts")
        .Response["parsed"] as BsonDocument;

    return result.Contains("replSet");
}

Upvotes: 2

Related Questions