Search code examples
c#mongodbmongodb-.net-driver

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;

Solution

  • 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();