先 NuGet兩個程式集 1:MongoDB.Driver、 2:MongoDB.Bson namespace ConsoleApp1{ /// <summary> /// MongoDb幫助類 /// </summary> /// <summary> /// MongoDb幫助類 /// </su ...
先 NuGet兩個程式集 1:MongoDB.Driver、 2:MongoDB.Bson
namespace ConsoleApp1
{
/// <summary>
/// MongoDb幫助類
/// </summary>
/// <summary>
/// MongoDb幫助類
/// </summary>
public class DB
{
private static readonly string connStr = "mongodb://127.0.0.1:27017";//GlobalConfig.Settings["mongoConnStr"];
private static readonly string dbName = "school";//GlobalConfig.Settings["mongoDbName"];
private static IMongoDatabase db = null;
private static readonly object lockHelper = new object();
private DB() { }
public static IMongoDatabase GetDb()
{
if (db == null)
{
lock (lockHelper)
{
if (db == null)
{
var client = new MongoClient(connStr);
db = client.GetDatabase(dbName);
}
}
}
return db;
}
}
public class MongoDbHelper<T>
{
private IMongoDatabase db = null;
private IMongoCollection<T> collection = null;
public MongoDbHelper()
{
this.db = DB.GetDb();
collection = db.GetCollection<T>(typeof(T).Name);
}
/// <summary>
/// 新增
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public T Insert(T entity)
{
var flag = ObjectId.GenerateNewId();
entity.GetType().GetProperty("_id").SetValue(entity, flag);
collection.InsertOneAsync(entity);
return entity;
}
/// <summary>
/// 修改一個值
/// </summary>
/// <param name="express"></param>
/// <param name="field"></param>
/// <param name="value"></param>
public bool Modify(Expression<Func<T, bool>> express, object updateField)
{
if (updateField == null) return false;
var props = updateField.GetType().GetProperties();
var field = props[0].Name;
var value = props[0].GetValue(updateField);
var updated = Builders<T>.Update.Set(field, value);
UpdateResult result = collection.UpdateOneAsync(express, updated).Result;
return result.ModifiedCount > 0 ? true : false;
}
/// <summary>
/// 更新
/// </summary>
/// <param name="entity"></param>
public bool Update(Expression<Func<T, bool>> express, T entity)
{
try
{
var old = collection.Find(express).ToList().FirstOrDefault();
foreach (var prop in entity.GetType().GetProperties())
{
if (!prop.Name.Equals("_id"))
{
var newValue = prop.GetValue(entity);
var oldValue = old.GetType().GetProperty(prop.Name).GetValue(old);
if (newValue != null)
{
if (oldValue == null)
oldValue = "";
if (!newValue.ToString().Equals(oldValue.ToString()))
{
old.GetType().GetProperty(prop.Name).SetValue(old, newValue.ToString());
}
}
}
}
// var filter = Builders<T>.Filter.Eq("Id", entity.Id);
ReplaceOneResult result = collection.ReplaceOneAsync(express, old).Result;
if (result.ModifiedCount > 0)
{
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
var aaa = ex.Message + ex.StackTrace;
throw;
}
}
/// <summary>
/// 刪除
/// </summary>
/// <param name="entity"></param>
public bool Delete(Expression<Func<T, bool>> express)
{
DeleteResult result = collection.DeleteOneAsync(express).Result;
return result.DeletedCount > 0 ? true : false;
}
/// <summary>
/// 查詢條件查詢數據
/// </summary>
/// <returns></returns>
public List<T> QueryAll(Expression<Func<T, bool>> express)
{
return collection.Find(express).ToList();
}
/// <summary>
/// 根據條件查詢一條數據
/// </summary>
/// <param name="express"></param>
/// <returns></returns>
public T QueryByFirst(Expression<Func<T, bool>> express)
{
return collection.Find(express).ToList().FirstOrDefault();
}
/// <summary>
/// 批量添加
/// </summary>
/// <param name="list"></param>
public void InsertBatch(List<T> list)
{
collection.InsertManyAsync(list);
}
/// <summary>
/// 根據Id批量刪除
/// </summary>
public bool DeleteBatch(List<ObjectId> list)
{
var filter = Builders<T>.Filter.In("_id", list);
DeleteResult result = collection.DeleteManyAsync(filter).Result;
return result.DeletedCount > 0 ? true : false;
}
}
}