C#操作MongoDB,看我这⼀篇就够了!
⼀、准备⼯作
⼯欲善其事必先利其器,⾸先呢咱们得下载好C#程序⾥⾯可以驱动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>
/// </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
reverse反义词{
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;
mysql菜鸟教程增删改查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
{c语言延时函数sleep
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);
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论