因为MongoDb 跨平台,可以免费使用,读写效率高,集群搭建简单,可以水平扩展等各种因素。
我决定研究一下Mongodb,在查看了相关文档后发现它对C#的支持不错,而且还有现成的C#的驱动,
新版的驱动还支持Linq,因为复杂的查询可以交给Linq去实现。正因为官方的驱动很强大。
刚开始接触时发现在大量的东西要去了解,为了能快速处理简单的项目,我对官方驱动做了进一步封装。项目中需要引入官方提供的dll,下载地址
下载好后解压到相应目录,将里面的dll引入到项目下(如红框所示)
以下为我封装的一些简单的增删改查操作
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MongoDB.Driver;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using System.Linq.Expressions; namespace Langu.DbHelper
{
/// <summary>
/// MongoDb 数据库操作类
/// </summary>
public class MongoHelper<T> where T : BaseEntity
{
/// <summary>
/// 数据库对象
/// </summary>
private IMongoDatabase database;
/// <summary>
/// 构造函数
/// </summary>
/// <param name="conString">连接字符串</param>
public MongoHelper(String conString)
{
var url = new MongoUrl(conString);
MongoClientSettings mcs = MongoClientSettings.FromUrl(url);
mcs.MaxConnectionLifeTime = TimeSpan.FromMilliseconds();
var client = new MongoClient(mcs);
this.database = client.GetDatabase(url.DatabaseName);
}
/// <summary>
/// 创建集合对象
/// </summary>
/// <param name="collName">集合名称</param>
///<returns>集合对象</returns>
private IMongoCollection<T> GetColletion(String collName)
{
return database.GetCollection<T>(collName);
} #region 增加
/// <summary>
/// 插入对象
/// </summary>
/// <param name="collName">集合名称</param>
/// <param name="t">插入的对象</param>
public void Insert(String collName, T t)
{
var coll = GetColletion(collName);
coll.InsertOne(t);
}
/// <summary>
/// 批量插入
/// </summary>
/// <param name="collName">集合名称</param>
/// <param name="ts">要插入的对象集合</param>
public void InsertBath(String collName, IEnumerable<T> ts)
{
var coll = GetColletion(collName);
coll.InsertMany(ts);
}
#endregion #region 删除
/// <summary>
/// 按BsonDocument条件删除
/// </summary>
/// <param name="collName">集合名称</param>
/// <param name="document">文档</param>
/// <returns></returns>
public Int64 Delete(String collName, BsonDocument document)
{
var coll = GetColletion(collName);
var result = coll.DeleteOne(document);
return result.DeletedCount;
}
/// <summary>
/// 按json字符串删除
/// </summary>
/// <param name="collName">集合名称</param>
/// <param name="json">json字符串</param>
/// <returns></returns>
public Int64 Delete(String collName, String json)
{
var coll = GetColletion(collName);
var result = coll.DeleteOne(json);
return result.DeletedCount;
}
/// <summary>
/// 按条件表达式删除
/// </summary>
/// <param name="collName">集合名称</param>
/// <param name="predicate">条件表达式</param>
/// <returns></returns>
public Int64 Delete(String collName, Expression<Func<T, Boolean>> predicate)
{
var coll = GetColletion(collName);
var result = coll.DeleteOne(predicate);
return result.DeletedCount;
}
/// <summary>
/// 按检索条件删除
/// 建议用Builders<T>构建复杂的查询条件
/// </summary>
/// <param name="collName">集合名称</param>
/// <param name="filter">条件</param>
/// <returns></returns>
public Int64 Delete(String collName, FilterDefinition<T> filter)
{
var coll = GetColletion(collName);
var result = coll.DeleteOne(filter);
return result.DeletedCount;
}
#endregion #region 修改
/// <summary>
/// 修改文档
/// </summary>
/// <param name="collName">集合名称</param>
/// <param name="filter">修改条件</param>
/// <param name="update">修改结果</param>
/// <param name="upsert">是否插入新文档(filter条件满足就更新,否则插入新文档)</param>
/// <returns></returns>
public Int64 Update(String collName, Expression<Func<T, Boolean>> filter, UpdateDefinition<T> update, Boolean upsert = false)
{
var coll = GetColletion(collName);
var result = coll.UpdateMany(filter, update, new UpdateOptions { IsUpsert = upsert });
return result.ModifiedCount;
}
/// <summary>
/// 用新对象替换新文档
/// </summary>
/// <param name="collName">集合名称</param>
/// <param name="filter">修改条件</param>
/// <param name="t">新对象</param>
/// <param name="upsert">是否插入新文档(filter条件满足就更新,否则插入新文档)</param>
/// <returns>修改影响文档数</returns>
public Int64 Update(String collName, Expression<Func<T, Boolean>> filter, T t, Boolean upsert = false)
{
var coll = GetColletion(collName);
BsonDocument document = t.ToBsonDocument<T>();
document.Remove("_id");
UpdateDocument update = new UpdateDocument("$set", document);
var result = coll.UpdateMany(filter, update, new UpdateOptions { IsUpsert = upsert });
return result.ModifiedCount;
}
#endregion /// <summary>
/// 查询,复杂查询直接用Linq处理
/// </summary>
/// <param name="collName">集合名称</param>
/// <returns>要查询的对象</returns>
public IQueryable<T> GetQueryable(String collName)
{
var coll = GetColletion(collName);
return coll.AsQueryable<T>();
}
#region 查询
#endregion
} /// <summary>
/// 实体基类,方便生成_id
/// </summary>
public class BaseEntity
{
[BsonRepresentation(BsonType.ObjectId)]
public String Id { get; set; }
/// <summary>
/// 给对象初值
/// </summary>
public BaseEntity()
{
this.Id = ObjectId.GenerateNewId().ToString();
}
}
}
做了一个简单的控制台调用(前提是mongodb服务已经打开,安装Mongodb以及打开部分有时间会一并发上来)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Langu.DbHelper;
using System.Threading;
using System.Linq.Expressions;
using MongoDB.Driver; namespace Client
{
class Program
{
static void Main(string[] args)
{
//连接字符串 127.0.0.1 服务器IP 27100 mongodb服务端口号 mydb 数据库名称
String conString = "mongodb://127.0.0.1:27100/mydb";
//实例化MongoHelper对象(泛型版本),构造函数要求传入连接字符串
MongoHelper<User> mongoHelper = new MongoHelper<User>(conString);
//查询集合 user中有多少数据量
var cnt = mongoHelper.GetQueryable("user").Count();
Console.WriteLine(cnt);
Console.ReadKey();
}
} internal class User : BaseEntity
{
public int Age { get; set; }
public String Name { get; set; }
}
}