3

I'm using Mongo with C# mongo driver(2.10).

I've managed to connect to it via a replica set via :

var dbClient = new MongoClient(
"mongodb://aaa:123@m.com:27017,m1.com:37017,m2.com:47017/dbtest?safe=true&connect=replicaset");

But then I read that I don't need to indicate connect=replicaset because I have multiple hosts.
Which is the opposite of what have been suggested here.

So now my connection is :

"mongodb://aaa:123@m.com:27017,m1.com:37017,m2.com:47017/dbtest?safe=true"

— it works.

But then I read the docs (and also here),and there is no connect=replicaset switch at all.

All there is the: replicaset=name switch.

Question:

What is the right way of declaring connection string (to be used with MongoClient C#) which uses a replica set ?

Royi Namir
  • 144,742
  • 138
  • 468
  • 792

1 Answers1

2

Lots have changed over the course of time with MongoDB C# driver. Your decision will need to be based on the version you are using.

First link written in 2014 for perl driver

SO link written in 2015 (when ver 2.2 was being used). There is no reference to connect=replicaset in any of the various versions documentation

Documentation This is what I would recommend using since its written by Mongo. Following the directions in these documenation, I have been able to use the MongoClient and MongoClient settings (exampled below).

Example

You can write your mongodb in a long string like you have above:

"mongodb://aaa:123@m.com:27017,m1.com:37017,m2.com:27017/dbtest?replicaSet=myRepl"

Recommendation

Instead of using a connection string like above, I would recommend using the native C# variables to connect to replica set. ConnectionMode specifies in the setting whether thats a ReplicaSet or Direct.

    var mongoClientSettings = new MongoClientSettings()
    {
        ConnectionMode = ConnectionMode.ReplicaSet,
        Credential = MongoCredential.CreateCredential("admin", "user", "pass"),
        ReplicaSetName = "ReplicaSetName",
        Servers = new List<MongoServerAddress>() { new MongoServerAddress("host", 27017), new MongoServerAddress("host2", 27017) }.ToArray(),
        ApplicationName = "NameOfYourApplicatino",
    };

    MongoClient client = new MongoClient(mongoClientSettings);

Since the client is thread safe, you can use that as a global variable as well.

Jawad
  • 11,028
  • 3
  • 24
  • 37
  • btw , looking at `"mongodb://aaa:123@m.com:27017,m1.com:37017,m2.com:27017/dbtest?replicaSet=myRepl"` , how can I know which is the primary or which is the secondary? because when I've declared them, I didn't specify which is which, I just [followed this article](https://stackoverflow.com/a/17438191/859154) – Royi Namir Jan 25 '20 at 16:39
  • You normally define all the servers you have in the replica set and when mongo client connects, it gets the primary and connects to that. Primary secondary is set up at mongodb level, not at connection settings. – Jawad Jan 25 '20 at 16:55