注:文档末尾附源码
演示操作环境(其他环境也可以):
开发环境:Windows 10 专业版
系统类型:64 位操作系统, 基于 x64 的处理器
IDE:Visual Studio 2019Community
数据库:MongoDB
创建一个项目名为MongoDBTest的Web API,net或者net core都可以,我这里以net core为例
需要在项目中引用MongoDB.Bson和MongoDB.Driver 注意是2.10.4版本的。
MongoDB.Bson是什么
BSON是一种类json的一种二进制形式的存储格式,简称Binary JSON,它和JSON一样,支持内嵌的文档对象和数组对象,但是BSON有JSON没有的一些数据类型,如Date和BinData类型。
BSON可以做为网络数据交换的一种存储形式,这个有点类似于Google的Protocol Buffer,但是BSON是一种schema-less的存储形式,它的优点是灵活性高,但它的缺点是空间利用率不是很理想,
BSON有三个特点:轻量性、可遍历性、高效性
{“hello":"world"} 这是一个BSON的例子,其中"hello"是key name,它一般是cstring类型,字节表示是cstring::= (byte*) "/x00" ,其中*表示零个或多个byte字节,/x00表示结束符;后面的"world"是value值,它的类型一般是string,double,array,binarydata等类型。
MongoDB.Bson在MongoDB中的使用
MongoDB使用了BSON这种结构来存储数据和网络数据交换。把这种格式转化成一文档这个概念(Document),因为BSON是schema-free的,所以在MongoDB中所对应的文档也有这个特征,这里的一个Document也可以理解成关系数据库中的一条记录(Record),只是这里的Document的变化更丰富一些,如Document可以嵌套。
MongoDB以BSON做为其存储结构的一种重要原因是其可遍历性。
MongoDB.Driver是什么
顾名思义,MongoDB.Driver是官网推出的连接MongoDB的驱动包,我们连接MongoDB需要依赖这个链接库。
引入 MongoDB.Bson和MongoDB.Driver包后就可以编写帮助类了,帮助类太多,帮助类可以自己拓展需要的方法,不过这里拓展的方法已经足够使用了。
创建一个上下文文件夹DbContexts,创建DBFactory帮助类,添加Bson和Driver的using引用,内容如下(文档末尾附源码里面有):
using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MongoDBTest.DbContexts
{
/// <summary>
/// Date 2021-07-12
/// Author:xiongze
/// Describe:MongoDB工具类
/// </summary>
/// <typeparam name="T"></typeparam>
public static class MongodbClient<T> where T : class
{
#region +MongodbInfoClient 获取mongodb实例
/// <summary>
/// 获取mongodb实例
/// </summary>
/// <param name="host">连接字符串,库,表</param>
/// <returns></returns>
public static IMongoCollection<T> MongodbInfoClient(MongodbHost host)
{
var mongoSettings = MongoClientSettings.FromConnectionString(host.Connection);
mongoSettings.GuidRepresentation = GuidRepresentation.PythonLegacy;
MongoClient client = new MongoClient(mongoSettings);
var dataBase = client.GetDatabase(host.DataBase);
return dataBase.GetCollection<T>(host.Table);
}
#endregion
}
public class MongodbHost
{
//public MongodbHost()
//{
// //Connection = CommonConfig.GetConnectionStrings().ConnectionStrings.MongoDBConnection;
// Connection =""; //这里是获取配置连接的mongodb连接,我这里先不指定,各种指定写法不一样(net和netcore获取不一样)
// DataBase = new MongoUrl(Connection).DatabaseName;
//}
public MongodbHost(string connectionString)
{
Connection = connectionString;
DataBase = new MongoUrl(connectionString).DatabaseName;
}
/// <summary>
/// 连接字符串
/// </summary>
public string Connection { get; set; }
/// <summary>
/// 库
/// </summary>
public string DataBase { get; set; }
/// <summary>
/// 表
/// </summary>
public string Table { get; set; }
}
public static class TMongodbHelper<T> where T : class, new()
{
#region +Add 添加一条数据
/// <summary>
/// 添加一条数据
/// </summary>
/// <param name="t">添加的实体</param>
/// <param name="host">mongodb连接信息</param>
/// <returns></returns>
public static int Add(MongodbHost host, T t)
{
try
{
var client = MongodbClient<T>.MongodbInfoClient(host);
client.InsertOne(t);
return 1;
}
catch
{
return 0;
}
}
#endregion
#region +AddAsync 异步添加一条数据
/// <summary>
/// 异步添加一条数据
/// </summary>
/// <param name="t">添加的实体</param>
/// <param name="host">mongodb连接信息</param>
/// <returns></returns>
public static async Task<int> AddAsync(MongodbHost host, T t)
{
try
{
var client = MongodbClient<T>.MongodbInfoClient(host);
await client.InsertOneAsync(t);
return 1;
}
catch
{
return 0;
}
}
#endregion
#region +InsertMany 批量插入
/// <summary>
/// 批量插入
/// </summary>
/// <param name="host">mongodb连接信息</param>
/// <param name="t">实体集合</param>
/// <returns></returns>
public static int InsertMany(MongodbHost host, List<T> t)
{
try
{
var client = MongodbClient<T>.MongodbInfoClient(host);
client.InsertMany(t);
return 1;
}
catch (Exception)
{
//throw ex;
return 0;
}
}
#endregion
#region +InsertManyAsync 异步批量插入
/// <summary>
/// 异步批量插入
/// </summary>
/// <param name="host">mongodb连接信息</param>
/// <param name="t">实体集合</param>
/// <returns></returns>
public static async Task<int> InsertManyAsync(MongodbHost host, List<T> t)
{
try
{
var client = MongodbClient<T>.MongodbInfoClient(host);
await client.InsertManyAsync(t);
return 1;
}
catch (Exception)
{
return 0;
}
}
public static async Task<int> AsyncInsertManyMethod(MongodbHost mongodb, T log)
{
int i = await TMongodbHelper<T>.InsertManyAsync(mongodb, new List<T> { log });
return i;
}
#endregion
#region +Update 修改一条数据
/// <summary>
/// 修改一条数据
/// </summary>
/// <param name="t">添加的实体</param>
/// <param name="host">mongodb连接信息</param>
/// <returns></returns>
public static UpdateResult Update(MongodbHost host, T t, string id)
{
try
{
var client = MongodbClient<T>.MongodbInfoClient(host);
//修改条件
FilterDefinition<T> filter = Builders<T>.Filter.Eq("_id", new ObjectId(id));
//要修改的字段
var list = new List<UpdateDefinition<T>>();
foreach (var item in t.GetType().GetProperties())
{
if (item.Name.ToLower() == "id") continue;
list.Add(Builders<T>.Update.Set(item.Name, item.GetValue(t)));
}
var updatefilter = Builders<T>.Update.Combine(list);
return client.UpdateOne(filter, updatefilter);
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region +UpdateAsync 异步修改一条数据
/// <summary>
/// 异步修改一条数据
/// </summary>
/// <param name="t">添加的实体</param>
/// <param name="host">mongodb连接信息</param>
/// <returns></returns>
public static async Task<UpdateResult> UpdateAsync(MongodbHost host, T t, string id)
{
try
{
var client = MongodbClient<T>.MongodbInfoClient(host);
//修改条件
FilterDefinition<T> filter = Builders<T>.Filter.Eq("_id", new ObjectId(id));
//要修改的字段
var list = new List<UpdateDefinition<T>>();
foreach (var item in t.GetType().GetProperties())
{
if (item.Name.ToLower() == "id") continue;
list.Add(Builders<T>.Update.Set(item.Name, item.GetValue(t)));
}
var updatefilter = Builders<T>.Update.Combine(list);
return await client.UpdateOneAsync(filter, updatefilter);
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region +UpdateManay 批量修改数据
/// <summary>
/// 批量修改数据
/// </summary>
/// <param name="dic">要修改的字段</param>
/// <param name="host">mongodb连接信息</param>
/// <param name="filter">修改条件</param>
/// <returns></returns>
public static UpdateResult UpdateManay(MongodbHost host, Dictionary<string, string> dic, FilterDefinition<T> filter)
{
try
{
var client = MongodbClient<T>.MongodbInfoClient(host);
T t = new T();
//要修改的字段
var list = new List<UpdateDefinition<T>>();
foreach (var item in t.GetType().GetProperties())
{
if (!dic.ContainsKey(item.Name)) continue;
var value = dic[item.Name];
list.Add(Builders<T>.Update.Set(item.Name, value));
}
var updatefilter = Builders<T>.Update.Combine(list);
return client.UpdateMany(filter, updatefilter);
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region +UpdateManayAsync 异步批量修改数据
/// <summary>
/// 异步批量修改数据
/// </summary>
/// <param name="dic">要修改的字段</param>
/// <param name="host">mongodb连接信息</param>
/// <param name="filter">修改条件</param>
/// <returns></returns>
public static async Task<UpdateResult> UpdateManayAsync(MongodbHost host, Dictionary<string, string> dic, FilterDefinition<T> filter)
{
try
{
var client = MongodbClient<T>.MongodbInfoClient(host);
T t = new T();
//要修改的字段
var list = new List<UpdateDefinition<T>>();
foreach (var item in t.GetType().GetProperties())
{
if (!dic.ContainsKey(item.Name)) continue;
var value = dic[item.Name];
list.Add(Builders<T>.Update.Set(item.Name, value));
}
var updatefilter = Builders<T>.Update.Combine(list);
return await client.UpdateManyAsync(filter, updatefilter);
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region Delete 删除一条数据
/// <summary>
/// 删除一条数据
/// </summary>
/// <param name="host">mongodb连接信息</param>
/// <param name="id">objectId</param>
/// <returns></returns>
public static DeleteResult Delete(MongodbHost host, string id)
{
try
{
var client = MongodbClient<T>.MongodbInfoClient(host);
FilterDefinition<T> filter = Builders<T>.Filter.Eq("_id", new ObjectId(id));
return client.DeleteOne(filter);
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region DeleteAsync 异步删除一条数据
/// <summary>
/// 异步删除一条数据
/// </summary>
/// <param name="host">mongodb连接信息</param>
/// <param name="id">objectId</param>
/// <returns></returns>
public static async Task<DeleteResult> DeleteAsync(MongodbHost host, string id)
{
try
{
var client = MongodbClient<T>.MongodbInfoClient(host);
//修改条件
FilterDefinition<T> filter = Builders<T>.Filter.Eq("_id", new ObjectId(id));
return await client.DeleteOneAsync(filter);
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region DeleteMany 删除多条数据
/// <summary>
/// 删除一条数据
/// </summary>
/// <param name="host">mongodb连接信息</param>
/// <param name="filter">删除的条件</param>
/// <returns></returns>
public static DeleteResult DeleteMany(MongodbHost host, FilterDefinition<T> filter)
{
try
{
var client = MongodbClient<T>.MongodbInfoClient(host);
return client.DeleteMany(filter);
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region DeleteManyAsync 异步删除多条数据
/// <summary>
/// 异步删除多条数据
/// </summary>
/// <param name="host">mongodb连接信息</param>
/// <param name="filter">删除的条件</param>
/// <returns></returns>
public static async Task<DeleteResult> DeleteManyAsync(MongodbHost host, FilterDefinition<T> filter)
{
try
{
var client = MongodbClient<T>.MongodbInfoClient(host);
return await client.DeleteManyAsync(filter);
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region Count 根据条件获取总数
/// <summary>
/// 根据条件获取总数
/// </summary>
/// <param name="host">mongodb连接信息</param>
/// <param name="filter">条件</param>
/// <returns></returns>
public static long Count(MongodbHost host, FilterDefinition<T> filter)
{
try
{
var client = MongodbClient<T>.MongodbInfoClient(host);
return client.CountDocuments(filter);
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region CountAsync 异步根据条件获取总数
/// <summary>
/// 异步根据条件获取总数
/// </summary>
/// <param name="host">mongodb连接信息</param>
/// <param name="filter">条件</param>
/// <returns></returns>
public static async Task<long> CountAsync(MongodbHost host, FilterDefinition<T> filter)
{
try
{
var client = MongodbClient<T>.MongodbInfoClient(host);
return await client.CountDocumentsAsync(filter);
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region FindOne 根据id查询一条数据
/// <summary>
/// 根据id查询一条数据
/// </summary>
/// <param name="host">mongodb连接信息</param>
/// <param name="id">objectid</param>
/// <param name="field">要查询的字段,不写时查询全部</param>
/// <returns></returns>
public static T FindOne(MongodbHost host, string id, string[] field = null)
{
try
{
var client = MongodbClient<T>.MongodbInfoClient(host);
FilterDefinition<T> filter = Builders<T>.Filter.Eq("_id", new ObjectId(id));
//不指定查询字段
if (field == null || field.Length == 0)
{
return client.Find(filter).FirstOrDefault<T>();
}
//制定查询字段
var fieldList = new List<ProjectionDefinition<T>>();
for (int i = 0; i < field.Length; i++)
{
fieldList.Add(Builders<T>.Projection.Include(field[i].ToString()));
}
var projection = Builders<T>.Projection.Combine(fieldList);
fieldList?.Clear();
return client.Find(filter).Project<T>(projection).FirstOrDefault<T>();
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region FindOneAsync 异步根据id查询一条数据
/// <summary>
/// 异步根据id查询一条数据
/// </summary>
/// <param name="host">mongodb连接信息</param>
/// <param name="id">objectid</param>
/// <returns></returns>
public static async Task<T> FindOneAsync(MongodbHost host, string id, string[] field = null)
{
try
{
var client = MongodbClient<T>.MongodbInfoClient(host);
FilterDefinition<T> filter = Builders<T>.Filter.Eq("_id", new ObjectId(id));
//不指定查询字段
if (field == null || field.Length == 0)
{
return await client.Find(filter).FirstOrDefaultAsync();
}
//制定查询字段
var fieldList = new List<ProjectionDefinition<T>>();
for (int i = 0; i < field.Length; i++)
{
fieldList.Add(Builders<T>.Projection.Include(field[i].ToString()));
}
var projection = Builders<T>.Projection.Combine(fieldList);
fieldList?.Clear();
return await client.Find(filter).Project<T>(projection).FirstOrDefaultAsync();
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region FindList 查询集合
/// <summary>
/// 查询集合
/// </summary>
/// <param name="host">mongodb连接信息</param>
/// <param name="filter">查询条件</param>
/// <param name="field">要查询的字段,不写时查询全部</param>
/// <param name="sort">要排序的字段</param>
/// <returns></returns>
public static List<T> FindList(MongodbHost host, FilterDefinition<T> filter, string[] field = null, SortDefinition<T> sort = null)
{
try
{
var client = MongodbClient<T>.MongodbInfoClient(host);
//不指定查询字段
if (field == null || field.Length == 0)
{
if (sort == null) return client.Find(filter).ToList();
//进行排序
return client.Find(filter).Sort(sort).ToList();
}
//制定查询字段
var fieldList = new List<ProjectionDefinition<T>>();
for (int i = 0; i < field.Length; i++)
{
fieldList.Add(Builders<T>.Projection.Include(field[i].ToString()));
}
var projection = Builders<T>.Projection.Combine(fieldList);
fieldList?.Clear();
if (sort == null) return client.Find(filter).Project<T>(projection).ToList();
//排序查询
return client.Find(filter).Sort(sort).Project<T>(projection).ToList();
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region FindListAsync 异步查询集合
/// <summary>
/// 异步查询集合
/// </summary>
/// <param name="host">mongodb连接信息</param>
/// <param name="filter">查询条件</param>
/// <param name="field">要查询的字段,不写时查询全部</param>
/// <param name="sort">要排序的字段</param>
/// <returns></returns>
public static async Task<List<T>> FindListAsync(MongodbHost host, FilterDefinition<T> filter, string[] field = null, SortDefinition<T> sort = null)
{
try
{
var client = MongodbClient<T>.MongodbInfoClient(host);
//不指定查询字段
if (field == null || field.Length == 0)
{
if (sort == null) return await client.Find(filter).ToListAsync();
return await client.Find(filter).Sort(sort).ToListAsync();
}
//制定查询字段
var fieldList = new List<ProjectionDefinition<T>>();
for (int i = 0; i < field.Length; i++)
{
fieldList.Add(Builders<T>.Projection.Include(field[i].ToString()));
}
var projection = Builders<T>.Projection.Combine(fieldList);
fieldList?.Clear();
if (sort == null) return await client.Find(filter).Project<T>(projection).ToListAsync();
//排序查询
return await client.Find(filter).Sort(sort).Project<T>(projection).ToListAsync();
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region FindListByPage 分页查询集合
/// <summary>
/// 分页查询集合
/// </summary>
/// <param name="host">mongodb连接信息</param>
/// <param name="filter">查询条件</param>
/// <param name="pageIndex">当前页</param>
/// <param name="pageSize">页容量</param>
/// <param name="count">总条数</param>
/// <param name="field">要查询的字段,不写时查询全部</param>
/// <param name="sort">要排序的字段</param>
/// <returns></returns>
public static List<T> FindListByPage(MongodbHost host, FilterDefinition<T> filter, int pageIndex, int pageSize, out long count, string[] field = null, SortDefinition<T> sort = null)
{
try
{
var client = MongodbClient<T>.MongodbInfoClient(host);
count = client.CountDocuments(filter);
//不指定查询字段
if (field == null || field.Length == 0)
{
if (sort == null) return client.Find(filter).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToList();
//进行排序
return client.Find(filter).Sort(sort).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToList();
}
//制定查询字段
var fieldList = new List<ProjectionDefinition<T>>();
for (int i = 0; i < field.Length; i++)
{
fieldList.Add(Builders<T>.Projection.Include(field[i].ToString()));
}
var projection = Builders<T>.Projection.Combine(fieldList);
fieldList?.Clear();
//不排序
if (sort == null) return client.Find(filter).Project<T>(projection).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToList();
//排序查询
return client.Find(filter).Sort(sort).Project<T>(projection).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToList();
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region FindListByPageAsync 异步分页查询集合
/// <summary>
/// 异步分页查询集合
/// </summary>
/// <param name="host">mongodb连接信息</param>
/// <param name="filter">查询条件</param>
/// <param name="pageIndex">当前页</param>
/// <param name="pageSize">页容量</param>
/// <param name="field">要查询的字段,不写时查询全部</param>
/// <param name="sort">要排序的字段</param>
/// <returns></returns>
public static async Task<List<T>> FindListByPageAsync(MongodbHost host, FilterDefinition<T> filter, int pageIndex, int pageSize, string[] field = null, SortDefinition<T> sort = null)
{
try
{
var client = MongodbClient<T>.MongodbInfoClient(host);
//不指定查询字段
if (field == null || field.Length == 0)
{
if (sort == null) return await client.Find(filter).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToListAsync();
//进行排序
return await client.Find(filter).Sort(sort).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToListAsync();
}
//制定查询字段
var fieldList = new List<ProjectionDefinition<T>>();
for (int i = 0; i < field.Length; i++)
{
fieldList.Add(Builders<T>.Projection.Include(field[i].ToString()));
}
var projection = Builders<T>.Projection.Combine(fieldList);
fieldList?.Clear();
//不排序
if (sort == null) return await client.Find(filter).Project<T>(projection).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToListAsync();
//排序查询
return await client.Find(filter).Sort(sort).Project<T>(projection).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToListAsync();
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region Save 替换原数据表列 (字段删除添加)
public static T Save(MongodbHost host, FilterDefinition<T> filter, T t)
{
try
{
var client = MongodbClient<T>.MongodbInfoClient(host);
return client.FindOneAndReplace(filter, t);
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region SaveAsync 替换原数据表列 (字段删除添加)
public static async Task<T> SaveAsync(MongodbHost host, FilterDefinition<T> filter, T t)
{
try
{
var client = MongodbClient<T>.MongodbInfoClient(host);
return await client.FindOneAndReplaceAsync(filter, t);
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
}
}
写好工具类我们就可以直接写增删改查了。
先定义实体类,下面就不在重复说定义实体了。
[BsonIgnoreExtraElements] //忽略增加项(MongoDB是文档型数据库,所以数据字段是根据传入的数据自动增加的,如果不忽略,增加项,查询返回实体就少了字段报错,当然也可以查询指定字段)
public class empty_collection
{
public ObjectId _id { get; set; } //主键
public string Name { get; set; } //姓名
public List<ClassTable> ClassTable { get; set; } //数据集合
public DateTime CreateDate { get; set; } //创建时间
}
public class ClassTable
{
public string ItemName { get; set; } //键名
public string ItemValue { get; set; } //值
}
//返回类型实体
public class ResultInfo
{
public int code { get; set; }
public string message { get; set; }
public object result { get; set; }
}
编写插入方法,注意看里面的注释,数据库连接的字符串格式、传值的类型等都有详细注释,这里就不进行啰嗦,直接上菜。
//插入
//GET api/values/InsertDate
[HttpGet("InsertDate")]
public JsonResult InsertDate()
{
ResultInfo res = new ResultInfo();
try
{
//连接mongodb的固定格式,应该写在配置里面,由于这里做演示,所以单独写
//user:user 第一个是用户名,第二个是密码
//localhost:27017 是你数据库的连接
//TestData 是你的数据库名称
var mongodbClient = "mongodb://user:user@localhost:27017/TestData";
MongodbHost mongodb = new MongodbHost(mongodbClient);
mongodb.DataBase = "TestData"; //数据库名
mongodb.Table = "empty_collection"; //操作的数据表(如果数据库没有定义表名,插入时会自动定义)
List<ClassTable> ctList = new List<ClassTable>();
int i = 0;
while(i<3)
{
ClassTable ct = new ClassTable();
switch (i)
{
case 0:
ct.ItemName = "班级";
ct.ItemValue = "取经天团";
break;
case 1:
ct.ItemName = "种族";
ct.ItemValue = "龙族";
break;
case 2:
ct.ItemName = "战斗力";
ct.ItemValue = "999999";
break;
}
ctList.Add(ct);
i++;
}
empty_collection model = new empty_collection()
{
Name = "白龙马",
ClassTable = ctList,
CreateDate=DateTime.Now
};
List<empty_collection> Listmodel = new List<empty_collection>();
Listmodel.Add(model);
var resCount=TMongodbHelper<empty_collection>.InsertMany(mongodb, Listmodel); // 插入多条数据
res.code = resCount;
res.message = resCount > 0 ? "操作成功" : "操作失败";
}
catch (Exception ex)
{
res.code = -2;
res.message = "操作失败:" + ex.Message;
}
return new JsonResult(res);
}
然后我们运行调用这个方法,查看一下数据库的值,很显然写入成功了。
编写查询方法,然后调用这个方法。
//查询
//GET api/values/GetDateList
[HttpGet("GetDateList")]
public JsonResult GetDateList()
{
ResultInfo res = new ResultInfo();
try
{
//连接mongodb的固定格式,应该写在配置里面,由于这里做演示,所以单独写
//user:user 第一个是用户名,第二个是密码
//localhost:27017 是你数据库的连接
//TestData 是你的数据库名称
var mongodbClient = "mongodb://user:user@localhost:27017/TestData";
MongodbHost mongodb = new MongodbHost(mongodbClient);
mongodb.DataBase = "TestData"; //数据库名
mongodb.Table = "empty_collection"; //操作的数据表
#region 筛选条件(至少一个条件)
var list = new List<FilterDefinition<empty_collection>>();
//Gte 大于等于 Lte 小于等于
list.Add(Builders<empty_collection>.Filter.Gte("CreateDate", "2021-01-01")); //注意:MongoDB当前方法查询需要必传至少一个参数,否则会报错
var filter = Builders<empty_collection>.Filter.And(list);
#endregion
var GetList = TMongodbHelper<empty_collection>.FindList(mongodb, filter).ToList(); //查询全部
//var GetList = TMongodbHelper<empty_collection>.FindListByPage(mongodb, filter, 1, 5, out count).ToList(); //分页查询
res.code = 0;
res.message = "查询成功";
res.result = GetList;
}
catch (Exception ex)
{
res.code = -2;
res.message = ex.Message;
}
return new JsonResult(res);
}
需要注意的是,查询语句的数据库交互至少有一个条件
编写修改方法,然后调用这个方法。
//修改
//GET api/values/UpdateDate
[HttpGet("UpdateDate")]
public JsonResult UpdateDate()
{
ResultInfo res = new ResultInfo();
try
{
//连接mongodb的固定格式,应该写在配置里面,由于这里做演示,所以单独写
//user:user 第一个是用户名,第二个是密码
//localhost:27017 是你数据库的连接
//TestData 是你的数据库名称
var mongodbClient = "mongodb://user:user@localhost:27017/TestData";
MongodbHost mongodb = new MongodbHost(mongodbClient);
mongodb.DataBase = "TestData"; //数据库名
mongodb.Table = "empty_collection"; //操作的数据表
//需要修改的条件
var UpdateList = new List<FilterDefinition<empty_collection>>();
UpdateList.Add(Builders<empty_collection>.Filter.Gte("CreateDate", "2021-01-01")); //注意:MongoDB当前方法查询需要必传至少一个参数,否则会报错
UpdateList.Add(Builders<empty_collection>.Filter.Eq("Name", "白龙马"));
var filterList = Builders<empty_collection>.Filter.And(UpdateList);
//需要修改后的值
Dictionary<string, string> dicList = new Dictionary<string, string>();
dicList.Add("Name", "南无八部天龙广力菩萨");
dicList.Add("CreateDate", DateTime.Now.ToString());
var resCount = TMongodbHelper<empty_collection>.UpdateManay(mongodb, dicList, filterList);
res.code = resCount.ModifiedCount > 0 ? 0 : -2;
res.message = resCount.ModifiedCount > 0 ? "操作成功" : "操作失败";
}
catch (Exception ex)
{
res.message = "操作失败:" + ex.Message;
}
return new JsonResult(res);
}
编写删除方法,然后调用这个方法。
//删除
//GET api/values/DeleteDate
[HttpGet("DeleteDate")]
public JsonResult DeleteDate()
{
ResultInfo res = new ResultInfo();
try
{
//连接mongodb的固定格式,应该写在配置里面,由于这里做演示,所以单独写
//user:user 第一个是用户名,第二个是密码
//localhost:27017 是你数据库的连接
//TestData 是你的数据库名称
var mongodbClient = "mongodb://user:user@localhost:27017/TestData";
MongodbHost mongodb = new MongodbHost(mongodbClient);
mongodb.DataBase = "TestData"; //数据库名
mongodb.Table = "empty_collection"; //操作的数据表
#region 筛选条件(至少一个条件)
var list = new List<FilterDefinition<empty_collection>>();
//Gte 大于等于 Lte 小于等于
list.Add(Builders<empty_collection>.Filter.Gte("CreateDate", "2021-01-01")); //注意:MongoDB当前方法查询需要必传至少一个参数,否则会报错
list.Add(Builders<empty_collection>.Filter.Eq("Name", "南无八部天龙广力菩萨"));
var filter = Builders<empty_collection>.Filter.And(list);
#endregion
var resCount = TMongodbHelper<empty_collection>.DeleteMany(mongodb, filter);
res.code = resCount.DeletedCount > 0 ? 0 : -2;
res.message = resCount.DeletedCount > 0 ? "操作成功" : "操作失败";
}
catch (Exception ex)
{
res.message = "操作失败:" + ex.Message;
}
return new JsonResult(res);
}
https://gitee.com/xiongze/MongoDBTest.git
https://gitee.com/xiongze/MongoDBTest
NoSql非关系型数据库之MongoDB在项目中的初步应用我们就介绍到这里了,
有想法其他想法的可以在评论区留言讨论。