一、准备工作
工欲善其事必先利其器,首先呢咱们得下载好C#程序里面可以驱动mongodb的组件:
走起官网:C#操作mongodb组件下载
菜鸟教程也上一上:mongodb菜鸟教程
dll下载下来之后有这几个,都引用上,不要省,哈哈!个人还是习惯直接下载下来,不走Nget的模式,那玩意菜鸟学不会。
为啥要加上xml呢,这你就不懂了,你难道没发现加了之后使用方法的时候,有了说明了么?就是这么优秀的一个操作。
二、开始实操增删改查
做好准备工作,下面咱们开始实操,把增删改查给你走一遍,看好喽,打起精神!
话不多话,咱先上代码,以后看到只说不做,特别是不放完整源代码的博主,咱们就得讲他耍流氓,咱可不做这类型的人,直接贴代码,优秀的人做事一向就是这么直接。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;
namespace MongoDbSpider
{
/// <summary>
/// MongoDb 数据库操作类
/// </summary>
public class MongoDbHelper
{
/// <summary>
/// 数据库对象
/// </summary>
private IMongoDatabase _dataBase;
/// <summary>
/// 构造函数
/// </summary>
/// <param name="conStrMdb">连接字符串</param>
public MongoDbHelper(string conStrMdb)
{
this._dataBase = GetDb(conStrMdb);
}
/// <summary>
/// 若没有,根据传入的数据库名字来生成对应的数据库名,否则,返回db
/// </summary>
/// <param name="conStrMdb">数据库连接</param>
/// <returns></returns>
public IMongoDatabase GetDb(string conStrMdb)
{
var db = new MongoClient(conStrMdb).GetDatabase(new MongoUrlBuilder(conStrMdb).DatabaseName);
return db;
}
/// <summary>
/// 创建集合对象
/// </summary>
/// <param name="collName">集合名称</param>
///<returns>集合对象</returns>
private IMongoCollection<T> GetColletion<T>(string collName)
{
return _dataBase.GetCollection<T>(collName);
}
/// <summary>
/// 获取指定数据库集合中的所有的文档
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="tableName">表名</param>
/// <returns></returns>
public List<T> FindAll<T>(string tableName)
{
List<T> list = new List<T>();
try
{
var collection = GetColletion<T>(collName: tableName);
FilterDefinition<T> filter = Builders<T>.Filter.Empty;
list = collection.Find<T>(filter).ToList<T>();
}
catch(Exception ex)
{
CLog.DbLog(ex.Message, "MongoDbHelper.FindAll");
}
return list;
}
/// <summary>
/// 插入对象
/// </summary>
/// <param name="collName">集合名称</param>
/// <param name="document">插入的对象</param>
/// <returns>异常返回-101</returns>
public DbMessage Insert<T>(string collName, T document)
{
try
{
var coll = GetColletion<T>(collName);
coll.InsertOne(document);
return new DbMessage { Ex = string.Empty, iFlg = 1 };
}
catch (Exception ex)
{
CLog.DbLog(ex.Message, "MongoDbHelper.Insert");
return new DbMessage { Ex = ex.Message, iFlg = -101 };
}
}
/// <summary>
/// 批量插入
/// </summary>
/// <param name="collName">集合名称</param>
/// <param name="documents">要插入的对象集合</param>
/// <returns>异常返回-101</returns>
public DbMessage InsertMany<T>(string collName, List<T> documents)
{
try
{
var coll = GetColletion<T>(collName);
coll.InsertMany(documents);
return new DbMessage { Ex = string.Empty, iFlg = documents.Count };
}
catch (Exception ex)
{
CLog.DbLog(ex.Message, "MongoDbHelper.InsertMany");
return new DbMessage { Ex = ex.Message, iFlg = -101 };
}
}
/// <summary>
/// 修改文档
/// </summary>
/// <param name="collName">集合名称</param>
/// <param name="filter">修改条件</param>
/// <param name="update">修改结果</param>
/// <param name="upsert">是否插入新文档(filter条件满足就更新,否则插入新文档)</param>
/// <returns>修改影响文档数,异常返回-101</returns>
public DbMessage Update<T>(string collName, Expression<Func<T, Boolean>> filter, UpdateDefinition<T> update, Boolean upsert = false)
{
try
{
var coll = GetColletion<T>(collName);
var result = coll.UpdateMany(filter, update, new UpdateOptions { IsUpsert = upsert });
return new DbMessage { Ex = string.Empty, iFlg = result.ModifiedCount };
}
catch (Exception ex)
{
CLog.DbLog(ex.Message, "MongoDbHelper.Update");
return new DbMessage { Ex = ex.Message, iFlg = -101 };
}
}
/// <summary>
/// 用新对象替换新文档
/// </summary>
/// <param name="collName">集合名称</param>
/// <param name="filter">修改条件</param>
/// <param name="t">新对象</param>
/// <param name="upsert">是否插入新文档(filter条件满足就更新,否则插入新文档)</param>
/// <returns>修改影响文档数,异常返回-101</returns>
public DbMessage Update<T>(string collName, Expression<Func<T, Boolean>> filter, T t, Boolean upsert = false)
{
try
{
var coll = GetColletion<T>(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 new DbMessage { Ex = string.Empty, iFlg = result.ModifiedCount };
}
catch (Exception ex)
{
CLog.DbLog(ex.Message, "MongoDbHelper.Update");
return new DbMessage { Ex = ex.Message, iFlg = -101 };
}
}
/// <summary>
/// 按BsonDocument条件删除
/// </summary>
/// <param name="collName">集合名称</param>
/// <param name="document">文档</param>
/// <returns>异常返回-101</returns>
public DbMessage Delete<T>(string collName, BsonDocument document)
{
try
{
var coll = GetColletion<T>(collName);
var result = coll.DeleteOne(document);
return new DbMessage { Ex = string.Empty, iFlg = result.DeletedCount };
}
catch(Exception ex)
{
CLog.DbLog(ex.Message, "MongoDbHelper.Delete");
return new DbMessage { Ex = ex.Message, iFlg = -101 };
}
}
/// <summary>
/// 按条件表达式删除
/// </summary>
/// <param name="collName">集合名称</param>
/// <param name="predicate">条件表达式</param>
/// <returns>异常返回-101</returns>
public DbMessage Delete<T>(string collName, Expression<Func<T, Boolean>> predicate)
{
try
{
var coll = GetColletion<T>(collName);
var result = coll.DeleteOne(predicate);
return new DbMessage { Ex = string.Empty, iFlg = result.DeletedCount };
}
catch (Exception ex)
{
CLog.DbLog(ex.Message, "MongoDbHelper.Delete");
return new DbMessage { Ex = ex.Message, iFlg = -101 };
}
}
/// <summary>
/// 按检索条件删除(建议用Builders-T构建复杂的查询条件)
/// </summary>
/// <param name="collName">集合名称</param>
/// <param name="filter">条件</param>
/// <returns></returns>
public DbMessage Delete<T>(string collName, FilterDefinition<T> filter)
{
try
{
var coll = GetColletion<T>(collName);
var result = coll.DeleteOne(filter);
return new DbMessage { Ex = string.Empty, iFlg = result.DeletedCount };
}
catch(Exception ex)
{
CLog.DbLog(ex.Message, "MongoDbHelper.Delete");
return new DbMessage { Ex = ex.Message, iFlg = -101 };
}
}
/// <summary>
/// 查询,复杂查询直接用Linq处理
/// </summary>
/// <param name="collName">集合名称</param>
/// <returns>要查询的对象</returns>
public IQueryable<T> GetQueryable<T>(string collName)
{
try
{
var coll = GetColletion<T>(collName);
return coll.AsQueryable<T>();
}
catch (Exception ex)
{
CLog.DbLog(ex.Message, "MongoDbHelper.GetQueryable");
return null;
}
}
}
public class DbMessage
{
/// <summary>
/// 反馈数量
/// </summary>
public long iFlg { get; set; }
/// <summary>
/// 反馈文字描述
/// </summary>
public string Ex { get; set; }
}
}
参考mysql的增删改查逻辑,实现mongodb的,内部实现数据库连接等细节性的东西,外部直接调用,整体来看属于三层结构的思维模式。下面上下实际使用场景的代码。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using ESpider.Spiders.MongoDbSpider;
using MongoDB.Bson;
using MongoDB.Driver;
namespace MongoDbSpider
{
class MyTest
{
public void Fun()
{
/*
* 所有的动作基于BsonDocument操作就对了
*/
//数据库连接,格式为mongodb://账号:密码@服务器地址:端口/数据库名
string conStrMdb = "mongodb://test:test@192.168.1.1:8888/test";
MongoDbSpider.MongoDbHelper mgDbHelper = new MongoDbSpider.MongoDbHelper(conStrMdb);
var db = mgDbHelper.GetDb(conStrMdb);
string colName = "person_index";
//查询,在这之前是没有数据的,自然也就查不出来数据,我们可以先给它插入一条数据
var cc = db.GetCollection<person_index>(colName);
var ccList = cc.Find(new BsonDocument()).ToList();
Console.WriteLine($"【当前集合{colName}数据量】>>>【{ccList.Count}】>>>{DateTime.Now}");
//建议以模型的方式插入数据,这样子字段类型是可控的
person_index personIndex = new person_index
{
_id系统会自动生成,不要赋值,插入之前移除掉,该字段用于接收模型用
//_id = null,
//这里使用Id_避免使用Id可能会与系统的起冲突
Id_ = 1,
FullName = "测试名称",
//mongodb存储的时间是UTC,会跟我们的本地时间相差8个小时。因此这边需要特殊处理一下时间
CreateTime = DateTime.Now.AddHours(8)
};
//转化为BsonDocument是为了方便移除_id
BsonDocument document = personIndex.ToBsonDocument();
document.Remove("_id");
var result = mgDbHelper.Insert(colName, document);
Console.WriteLine($"【插入】>>>【{result.iFlg}】>>>{DateTime.Now}");
//现在我们再查询试下,这里可以添加查询条件
BsonDocument document1 = new BsonDocument();
document1.Add("Id_", personIndex.Id_);
document1.Add("FullName", personIndex.FullName);
var cc1List = cc.Find(document1).ToList();
for (int i = 0; i < cc1List.Count; i++)
{
Console.WriteLine(cc1List[i].ToJson());
}
//更新,使用表达式树,实现更新逻辑,注意类型一定要跟字段对应上
UpdateDocument update = new UpdateDocument("$set", new BsonDocument() { { "CreateTime", DateTime.Now } });
Expression<Func<person_index, bool>> exp = (s => s.Id_ == personIndex.Id_ && s.FullName == personIndex.FullName);
var upResult = mgDbHelper.Update(colName, exp, update, false);
Console.WriteLine($"【更新】>>>【{upResult.iFlg}】>>>{DateTime.Now}");
//删除操作的话就不演示了,慎用!
Expression<Func<person_index, bool>> deleteExp = (s => s.Id_ == personIndex.Id_ && s.FullName == personIndex.FullName && s.CreateTime == personIndex.CreateTime);
//由于我们更新了日期,这里的删除操作应该是不会生效的
var deleteResult = mgDbHelper.Delete(colName, deleteExp);
Console.WriteLine($"【删除】>>>【{deleteResult.iFlg}】>>>{DateTime.Now}");
}
/// <summary>
/// 测试模型
/// </summary>
private class person_index
{
/// <summary>
/// 系统自带_id
/// </summary>
public object _id { get; set; }
/// <summary>
/// 自增长id
/// </summary>
public long Id_ { get; set; }
/// <summary>
/// 全称
/// </summary>
public string FullName { get; set; }
/// <summary>
/// 创建时间
/// </summary>
public DateTime CreateTime { get; set; }
}
}
}
结束语:文章描述性的文字说明不多,干货主要体现在代码层面,拿过去就能用的,尤秀娣魜就是折磨滴螚咁!