En primer lugar necesitamos declarar la siguiente Interface e implementarla en las clases que queremos enviar a MongoDB:
public interface IMongeable{int Id;}
Como podéis ver, tan solo es obligatorio disponer de ID (necesario como clave primaria en todas las colecciones [tablas] de MongoDB).
La clase que nos encapsulará el acceso a MongoDB desde C# es la siguiente:
using MongoDB;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
namespace Mongo
{
public static class Generic
{
private static string database_name = ConfigurationManager.AppSettings["Mongo_database"];
public static bool HasMongo() { return (ConfigurationManager.AppSettings["Mongo_active"] == "true"); }
public static MongoCollection getCollection<T>(string collection_name)
{
var server = MongoServer.Create(ConfigurationManager.AppSettings["Mongo_connectionstring"]);
var database = server.GetDatabase(database_name);
var s = database.CreateCollectionSettings<T>(collection_name);
s.ReadPreference = ReadPreference.Nearest;
return database.GetCollection(s);
}
public static IMongeable Get<T>(string collection_name, int id) where T : IMongeable
{
return getCollection<T>(collection_name).FindOneByIdAs<T>(id);
}
public static List<T> GetBy<T>(string collection_name, string field, string value) where T : IMongeable
{
return getCollection<T>(collection_name).FindAs<T>(new QueryDocument(field, value)).ToList<T>();
}
public static void Save<T>(string collection_name, T document) where T : IMongeable
{
getCollection<T>(collection_name).Save(document);
}
public static void Set<T>(string collection_name, int id, string field, string value) where T : IMongeable
{
getCollection<T>(collection_name).Update(Query<T>.EQ(a => a.Id, id), new UpdateDocument(field,value));
}
public static void Delete<T>(string collection_name, int id) where T: IMongeable
{
getCollection<T>(collection_name).Remove(Query<T>.EQ(a => a.Id, id));
}
}
}
using MongoDB.Driver;
using MongoDB.Driver.Builders;
namespace Mongo
{
public static class Generic
{
private static string database_name = ConfigurationManager.AppSettings["Mongo_database"];
public static bool HasMongo() { return (ConfigurationManager.AppSettings["Mongo_active"] == "true"); }
public static MongoCollection getCollection<T>(string collection_name)
{
var server = MongoServer.Create(ConfigurationManager.AppSettings["Mongo_connectionstring"]);
var database = server.GetDatabase(database_name);
var s = database.CreateCollectionSettings<T>(collection_name);
s.ReadPreference = ReadPreference.Nearest;
return database.GetCollection(s);
}
public static IMongeable Get<T>(string collection_name, int id) where T : IMongeable
{
return getCollection<T>(collection_name).FindOneByIdAs<T>(id);
}
public static List<T> GetBy<T>(string collection_name, string field, string value) where T : IMongeable
{
return getCollection<T>(collection_name).FindAs<T>(new QueryDocument(field, value)).ToList<T>();
}
public static void Save<T>(string collection_name, T document) where T : IMongeable
{
getCollection<T>(collection_name).Save(document);
}
public static void Set<T>(string collection_name, int id, string field, string value) where T : IMongeable
{
getCollection<T>(collection_name).Update(Query<T>.EQ(a => a.Id, id), new UpdateDocument(field,value));
}
public static void Delete<T>(string collection_name, int id) where T: IMongeable
{
getCollection<T>(collection_name).Remove(Query<T>.EQ(a => a.Id, id));
}
}
}
La clase que hemos creado nos permitirá realizar las siguientes acciones:
- Get por ID
- Get de una lista de objetos que cumplen una condición explícita.
- Save del objeto.
- Set único de un campo del objeto por ID.
- Delete por ID
Ejemplo de uso:
int id = 1;
MiObjetoData miObjeto1 = Mongo.Generic.Get<MiObjetoData>(" misobjetos", id)
Mongo.Generic.Save<MiObjetoData>("misobjetos", miObjeto1);
Si te ha gustado este post, compártelo ;)