mongodb.driver 2.4.4 c# 第一篇 数据库连接 增、删、改、查
第一步:NuGet下载驱动。
第二步:dbhelper编写
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Linq;
public class Db
{
private static IMongoDatabase db = null;
private static readonly object lockHelper = new object();
private Db() { }
public static IMongoDatabase GetDb(string connStr, string dbName)
{
if (db == null)
{
lock (lockHelper)
{
if (db == null)
{
var client = new MongoClient(connStr);
db = client.GetDatabase(dbName);
}
}
}
else
{
if (db.DatabaseNamespace.DatabaseName != dbName)
{
lock (lockHelper)
{
var client = new MongoClient(connStr);
db = client.GetDatabase(dbName);
}
}
}
return db;
}
}
public class MongoDbHelper<T> where T : MongoBaseEntity
{
private IMongoDatabase db = null;
private IMongoCollection<T> collection = null;
public MongoDbHelper(string constr, string dbname, string collectionname)
{
this.db = Db.GetDb(constr, dbname);
collection = db.GetCollection<T>(collectionname);
}
/// <summary>
/// 插入数据
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public T Insert(T entity)
{
var flag = ObjectId.GenerateNewId();
entity._id = flag;
collection.InsertOne(entity);
return entity;
}
/// <summary>
/// 更新实体
/// </summary>
/// <param name="entity"></param>
public bool Update(T entity)
{
var old = collection.Find(e => e._id.Equals(entity._id)).ToList().FirstOrDefault();
foreach (var prop in entity.GetType().GetProperties())
{
var newValue = prop.GetValue(entity);
var oldValue = old.GetType().GetProperty(prop.Name).GetValue(old);
if (newValue != null && oldValue != null)
{
if (!newValue.Equals(oldValue))
{
old.GetType().GetProperty(prop.Name).SetValue(old, newValue);
}
}
else
{
old.GetType().GetProperty(prop.Name).SetValue(old, newValue);
}
}
var filter = Builders<T>.Filter.Eq("_id", entity._id);
ReplaceOneResult result = collection.ReplaceOneAsync(filter, old).Result;
return result.ModifiedCount > 0 ? true : false;
}
/// <summary>
/// 根据ID删除数据(硬删)
/// </summary>
/// <param name="ID"></param>
public void Delete(string ID)
{
var filter = Builders<T>.Filter.Eq("_id", ID);
collection.DeleteOneAsync(filter);
}
/// <summary>
/// 查询所有数据
/// </summary>
/// <returns></returns>
public List<T> QueryAll()
{
var coll = collection.Find(FilterDefinition<T>.Empty);
coll.Options.NoCursorTimeout = false;
return coll.ToList();
}
}
public class MongoBaseEntity
{
public ObjectId _id { get; set; }
public string unique_id { get; set; }
}
第三步:调用
Entity 为你与mongdb数据映射的实体类
private MongoDbHelper<Entity> Mongodb_ComDb;
构造函数中 构建对象
Mongodb_ComDb = new MongoDbHelper<Entity>(“IP”, “DBName”, "collectionName");
// 增
Mongodb_ComDb.Insert(Entity);
//删
int id=100;
Mongodb_ComDb.Delete(id);
// 改
Mongodb_ComDb.Update(Entity);
// 查
Mongodb_ComDb.QueryAll();
最基本的mongodb数据库链接,增、删、改、查实现。 源码非编译器状态修改,如有问题可留言。或者微信(plit001)获取源码。