新建c#项目,在nuget中引入MongoDB.Driver驱动,然后新建一个MongoDBToolHelper类,将下面代码复制进去
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Hy.DBUtility.Common
{
/// <summary>
/// mongodb数据库帮助类
/// </summary>
public class MongoDBToolHelper
{
/// <summary>
/// 数据库名称
/// </summary>
public string ConnectionNamse { get; set; }
/// <summary>
/// 数据库连接字符串
/// </summary>
public string PBConStr { get; set; } = "";
public string connStr
{
get
{
try
{
string database = "";
var db = ConfigurationManager.ConnectionStrings[this.ConnectionNamse];
if (db != null)
{
database = db.ConnectionString;
}
else
{
database = ConfigurationManager.AppSettings[this.ConnectionNamse];
}
if (!string.IsNullOrEmpty(database))
{
return database;
}
else
{
if (!string.IsNullOrEmpty(PBConStr))
{
database = PBConStr;
}
}
return database;
}
catch (Exception ex)
{
return "";
}
}
}
/// <summary>
/// 获取数据库
/// </summary>
/// <returns></returns>
public MongoDatabase GetMongoDB()
{
return new MongoClient(connStr).GetServer().GetDatabase(ConnectionNamse);
}
public MongoCollection<BsonDocument> GetCol<T>()
{
return GetMongoDB().GetCollection(typeof(T).Name);
}
/// <summary>
/// 新增
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="entity"></param>
/// <returns></returns>
public T Add<T>(T entity)
{
var col = GetCol<T>();
col.Insert(entity);
return entity;
}
/// <summary>
/// 编辑
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="entity"></param>
/// <param name="id"></param>
public void Update<T>(T entity, string id)
{
var col = GetCol<T>();
ObjectId tId = new ObjectId(id);
BsonDocument bsd = BsonExtensionMethods.ToBsonDocument(entity);
IMongoQuery query = Query.EQ("_id", tId);
col.Update(query, new UpdateDocument(bsd));
}
/// <summary>
/// 编辑
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="entity"></param>
/// <param name="id"></param>
public void Update<T>(IMongoQuery query, IMongoUpdate update, bool updateMulti = false)
{
var col = GetCol<T>();
if (updateMulti)
{
col.Update(query, update, UpdateFlags.Multi);// 更新多条
return;
}
col.Update(query, update);
}
/// <summary>
/// 删除
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dics"></param>
public void Delete<T>(Dictionary<string, object> dics)
{
var col = GetCol<T>();
var query = new QueryDocument(dics);
col.Remove(query);
}
/// <summary>
/// 删除
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dics"></param>
public void Delete<T>(IMongoQuery query)
{
var col = GetCol<T>();
col.Remove(query);
}
/// <summary>
/// 删除所有数据
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dics"></param>
public void DeleteAll<T>()
{
var col = GetCol<T>();
col.RemoveAll();
}
/// <summary>
/// 删除
/// remark:根据ObjectId删除
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="id"></param>
public void Delete<T>(string id)
{
var col = GetCol<T>();
ObjectId tId = new ObjectId(id);
IMongoQuery query = Query.EQ("_id", tId);
col.Remove(query);
}
/// <summary>
/// 查找单个实体数据
/// </summary>
/// <param name="query"></param>
/// <returns></returns>
public T Find<T>(IMongoQuery query)
{
var col = GetCol<T>();
return col.FindAs<T>(query).FirstOrDefault();
}
/// <summary>
/// 查找单个实体数据
/// </summary>
/// <param name="query"></param>
/// <returns></returns>
public T FindById<T>(string id)
{
var col = GetCol<T>();
ObjectId tId = new ObjectId(id);
BsonDocument bsonDocument = col.FindOneById(tId);
T t = BsonSerializer.Deserialize<T>(bsonDocument);
return t;
}
/// <summary>
/// 查询全部
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public List<T> QueryList<T>()
{
var col = GetCol<T>();
var result = col.FindAllAs<T>();
return result.ToList();
}
/// <summary>
/// 根据条件查询
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dics"></param>
/// <returns></returns>
public List<T> QueryList<T>(Dictionary<string, object> dics)
{
var col = GetCol<T>();
var query = new QueryDocument(dics);
var result = col.FindAs<T>(query);
return result.ToList<T>();
}
/// <summary>
/// 分页查询
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public List<T> QueryPageList<T>(int pageIndex, int pageSize, IMongoQuery query, string[] sortFields)
{
var col = GetCol<T>();
var result = col.FindAs<T>(query).SetSortOrder(SortBy.Descending(sortFields))
.Skip((pageIndex - 1) * pageSize)
.Take(pageSize)
.ToList();
return result;
}
/// <summary>
/// 查询条数
/// </summary>
/// <param name="query"></param>
/// <returns></returns>
public long Count<T>(IMongoQuery query = null)
{
var col = GetCol<T>();
long n = col.Count(query);
return n;
}
}
/**
* 项目引用:MongoDB.Driver
* 操作集合实体案例:
* /// <summary>
/// 注意:实体名就是集合名称,必须一致
/// </summary>
[BsonIgnoreExtraElements]
public class TEST
{
public ObjectId _id { get; set; }
public string OrderId { get; set; }
public string OrderCode { get; set; }
}
连接字符串配置:
<appSettings>
<add key="TEST" value="mongodb://TEST:123456@127.0.0.1:27017/TEST"/>
</appSettings>
查询调用方式:
//var sd = MongoDBConfig.MongoDBToolHelper_TEST.QueryList<TEST>();
//var sd = MongoDBConfig.MongoDBToolHelper_TEST.QueryPageList<TEST>(1, 10, null, new string[] { "OrderId" });
//var mdoel = MongoDBConfig.MongoDBToolHelper_TEST.Find<TEST>( Query.EQ("OrderId", "111"));
var mdoel = MongoDBConfig.MongoDBToolHelper_TEST.FindById<TEST>("222");
注意:所有操作的T实体,实体名称必须与集合名称一致
*/
}
下面是mongodb配置类,同上操作,这里只封装了基本的操作,如果有其他的操作可以自行封装
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Hy.DBUtility.Common
{
/// <summary>
/// mongodb数据库配置类
/// </summary>
public class MongoDBConfig
{
private static MongoDBToolHelper _MongoDBToolHelper_TEST;
public static MongoDBToolHelper MongoDBToolHelper_TEST
{
get
{
if (_MongoDBToolHelper_TEST == null)
{
_MongoDBToolHelper_TEST = new MongoDBToolHelper();
_MongoDBToolHelper_TEST.ConnectionNamse = "TEST";
}
return _MongoDBToolHelper_TEST;
}
}
}
}