I have My Mongo DB set with a replica set of 3. One Primary and Two secondaries.
var connectionString = ConfigurationManager.AppSettings["MongoDBWriteCS"];
var client = new MongoClient(connectionString);
_MongoWriteServer = client.GetServer();
_WriteDatabase = _MongoWriteServer.GetDatabase("DBName");
_WriteDatabase.GetCollection<CollectionType>("CollectionName").Insert(Object);
When my code runs with the below connection string, it has no issues to insert records
<add key="MongoDBWriteCS" value="mongodb://username:password@10.0.0.0:27019/admin?w=0" />
But the problem is, since it is on replica set, my primary keeps changing when primary goes from 27019 to 27018 or 27017 inserts fails.
So I tried to change my connection string as more authentic Replica set connection string.
<add key="MongoDBWriteCS" value="mongodb://username:password@10.0.0.0:27017,10.0.0.0:27018,10.0.0.0:27019/admin?replicaSet=myRepSet&readPreference=primaryPreferred&w=0" />
It keeps failing with "No such host" or "unable to connect to a member",but with in the same line of code get list of collections works (I mean reads works only writes fails like insert or save commands)
I am using MongoDB 2.6.4
rs.status()
/* 0 */
{
"set" : "rbRepSet",
"date" : ISODate("2015-03-09T23:27:17.000Z"),
"myState" : 1,
"members" : [
{
"_id" : 0,
"name" : "haboMongo:27017",
"health" : 1,
"state" : 2,
"stateStr" : "SECONDARY",
"uptime" : 59570,
"optime" : Timestamp(1425941592, 5),
"optimeDate" : ISODate("2015-03-09T22:53:12.000Z"),
"lastHeartbeat" : ISODate("2015-03-09T23:27:16.000Z"),
"lastHeartbeatRecv" : ISODate("2015-03-09T23:27:17.000Z"),
"pingMs" : 0,
"syncingTo" : "haboMongo:27019"
},
{
"_id" : 1,
"name" : "haboMongo:27018",
"health" : 1,
"state" : 2,
"stateStr" : "SECONDARY",
"uptime" : 2220179,
"optime" : Timestamp(1425941592, 5),
"optimeDate" : ISODate("2015-03-09T22:53:12.000Z"),
"lastHeartbeat" : ISODate("2015-03-09T23:27:17.000Z"),
"lastHeartbeatRecv" : ISODate("2015-03-09T23:27:16.000Z"),
"pingMs" : 0,
"syncingTo" : "haboMongo:27019"
},
{
"_id" : 2,
"name" : "haboMongo:27019",
"health" : 1,
"state" : 1,
"stateStr" : "PRIMARY",
"uptime" : 2220202,
"optime" : Timestamp(1425941592, 5),
"optimeDate" : ISODate("2015-03-09T22:53:12.000Z"),
"electionTime" : Timestamp(1425100988, 1),
"electionDate" : ISODate("2015-02-28T05:23:08.000Z"),
"self" : true
}
],
"ok" : 1
}
rs.config()
/* 0 */
{
"_id" : "rbRepSet",
"version" : 3,
"members" : [
{
"_id" : 0,
"host" : "haboMongo:27017"
},
{
"_id" : 1,
"host" : "haboMongo:27018"
},
{
"_id" : 2,
"host" : "haboMongo:27019"
}
]
}