public class MongoHelper { private static IMongoDatabase GetDb(string constr, string dbName) { var db = new MongoClient(constr).GetDatabase(dbName); return db; } private static IMongoCollection<T> GetCT<T>(string constr, string dbName, string tableName) { return GetDb(constr, dbName).GetCollection<T>(tableName); } public static void Insert<T>(string constr, string dbName,string tableName,T document) { var collection = GetCT<T>(constr, dbName, tableName); collection.InsertOne(document); } public static void Insert<T>(string constr, string dbName, string tableName, IEnumerable<T> documents) { var collection = GetCT<T>(constr, dbName, tableName); collection.InsertMany(documents); } public static List<T> Find<T>(string constr, string dbName, string tableName, FilterDefinition<T> filter) { var collection = GetCT<T>(constr, dbName, tableName); return collection.Find<T>(filter).ToList<T>(); } public static List<T> Find<T>(string constr, string dbName, string tableName, FilterDefinition<T> filter,SortDefinition<T> sort) { var collection = GetCT<T>(constr, dbName, tableName); return collection.Find<T>(filter).Sort(sort).ToList<T>(); } public static List<T> Find<T>(string constr, string dbName, string tableName,int pageIndex,int pageSize, FilterDefinition<T> filter) { var collection = GetCT<T>(constr, dbName, tableName); return collection.Find<T>(filter).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToList<T>(); } public static bool Update<T>(string constr, string dbName, string tableName,FilterDefinition<T> filter,UpdateDefinition<T> update) { var collection = GetCT<T>(constr, dbName, tableName); var result = collection.UpdateMany(filter, update); if (result.ModifiedCount > 0) { return true; } return false; } public static bool Delete(string constr, string dbName, string tableName, BsonDocument filter) { var collection = GetCT<BsonDocument>(constr, dbName, tableName); DeleteResult result = collection.DeleteMany(filter); if (result != null && result.DeletedCount > 0) { return true; } return false; } }