I would like to know the most efficient way to create /close MongoDb Connections.
I have a set of Restful services (created using c#), some of them get data form a MongoDb and some POST data in.
public static MongoDatabase GetDatabase()
{
MongoServerSettings settings = new MongoServerSettings();
settings.Server = new MongoServerAddress("localhost", 27017);
MongoServer server = new MongoServer(settings);
var database = server.GetDatabase("RapidDataStream");
return database;
}
I use the above connection form each of my services, for example a service to list all sensors.
public List<Sensor> getPublicSensors()
{
List<Sensor> sensors = new List<Sensor>();
MongoDatabase mySensor = GetDatabase();
var query = Query.And(Query.EQ("User", BsonValue.Create("Public")));
var mySensorRecords = mySensor.GetCollection("sensor_meta_data").Find(query);
DataSet ds = new DataSet();
foreach (var rec in mySensorRecords)
{
Sensor sensor = new Sensor();
sensor.sensorId = rec["EnvId"].ToString();
for (int i = 2; i < rec.ElementCount; i++)
{
SensorObject so = new SensorObject();
so.fieldName = rec.GetElement(i).Name.ToString();
so.value = rec.GetElement(i).Value.ToString();
sensor.sensorObject.Add(so);
}
sensors.Add(sensor);
}
return sensors;
}
My question is that whether this is an efficient design or else how can I improve it?
Many Thanks.
I believe Mongo (or the driver) handles some things for us, so I use the Create method:
instead of creating a new instance. The
Createmethod will create a new instance or return an existing instance (it is unique per server settings).In fact, just to show you the actual method I use currently:
IMongoConfigis just a little DTO I use to specify, as you can see, the connection string and DB name I need – this combined with the workings ofMongoServer.Createmake it quite easy to handle connections to multiple databases from the same running code base.