user3287476
user3287476

Reputation: 93

MongoDb Connect to Replica Set Primary Issue C#

How do I get back the name of the primary database? Lets say database3 was primary

Thanks

var connString = "mongodb://database1,database2,database3/?replicaSet=repl";
var client = new MongoClient(connString);
var server = client.GetServer().Instances.FirstOrDefault(server => server.IsPrimary);
var address = server.Address;

Upvotes: 3

Views: 2320

Answers (3)

user3287476
user3287476

Reputation: 93

Thanks to Jaco for putting me on the right track I solved my problem by doing the following

public static string GetPrimaryDatabase()
{
    var mongoClient = new MongoClient(clientSettings);
    var server = mongoClient.GetServer();
    var database = server.GetDatabase("test");

    var cmd = new CommandDocument("isMaster", "1");
    var result = database.RunCommand(cmd);

        return result.Response.FirstOrDefault(
          response => response.ToString().Contains("primary")).Value.ToString();
}

Upvotes: 2

Alex
Alex

Reputation: 21766

Having looked at the source code of the MongoDB driver, there is no straightforward way to get the name of the primary server from the driver itself. However, you can query server name in MOngoDB by executing {isMaster:1} using RunCommand. You can then parse the primary server from the returned JSON document. This approach works regardless if you are connected to the primary or secondary server.

var mongoClient = new MongoClient(clientSettings);
var testDB = mongoClient.GetDatabase("test");
var cmd = new BsonDocument("isMaster", "1");
var result = testDB.RunCommand<BsonDocument>(cmd);
var primaryServer = result.Where(x => x.Name == "primary").FirstOrDefault().Value.ToString();

Upvotes: 2

Dmytro Shevchenko
Dmytro Shevchenko

Reputation: 34641

You really should not handle connecting to the right server yourself. The MongoDB driver handles that for you.

Just specify all of your servers in the connections string and the driver will connect to one of them and get replica set's current state on its own. The driver will then direct write operations to the current primary. Read operations may be directed to the primary, or any other server, depending on the read preference you specify.

You can read about forming replica set connection strings here: https://docs.mongodb.org/v3.0/reference/connection-string/

Upvotes: 2

Related Questions