后端:C#操作Mongodb用法笔记
MongoDB 是一个基于分布式文件存储的数据库。由 C++ 语言编写。旨在为 WEB 应用提供可扩展的高性能数据存储解决方案。今天主要给大家介绍一下C#编程语言下Mongodb的用法。开发环境为VS2015示例主要包括数据的增删改查、分页查询、文件存储等功能。有需要的朋友可以一起学习一下。
1、需要引用Mongodb程序集
MongoDB.Bson.dll
MongoDB.Driver.dll
2、创建Mongodb工具类库 MongodbHelper.cs
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using MongoDB.Driver.GridFS;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
namespace MongodbHelper
{
/// <summary>
/// MongoDB的基本增删改查
/// </summary>
public class MongodbTool
{
private readonly MongoDatabase _db;
//数据库默认地址
private readonly string host = ConfigurationManager.AppSettings["db_host"];
//数据库默认名称
private readonly string db_name = ConfigurationManager.AppSettings["db_name"];
public MongodbTool()
{
var client = new MongoClient(host); //ip及端口
var server = client.GetServer();
_db = server.GetDatabase(db_name); //数据库名称
}
#region 通用增删改查
/// <summary>
/// 新增单个实体模型 modifiy by 2020-11-11
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="entity"></param>
/// <returns>True:成功,False:失败</returns>
public bool Insert<T>(T entity)
{
bool isOk = true;
try
{
BsonDocument doc = entity.ToBsonDocument();
WriteConcernResult result = this._db.GetCollection(typeof(T).Name).Insert(doc);
isOk = result.Ok;
}
catch (Exception ex)
{
}
return isOk;
}
/// <summary>
/// 新增实体集合模型
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="entity"></param>
/// <returns>True:成功,False:失败</returns>
public bool Add<T>(IEnumerable<T> entity)
{
bool isOk = true;
try
{
int s = 1;
IEnumerable<WriteConcernResult> results = this._db.GetCollection(typeof(T).Name).InsertBatch(entity);
foreach (var item in results)
{
if (item.Ok)
isOk = true;
else
isOk = false;
}
}
catch (Exception ex)
{
}
return isOk;
}
/// <summary>
/// 查询单条数据
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="Field">查询属性字段</param>
/// <param name="Value">字段值</param>
/// <returns>返回当前实体</returns>
public T FindOne<T>(string Field, string Value)
{
T oneEntity = default(T);
try
{
FindOneArgs args = new FindOneArgs
{
Query = Query.EQ(Field, Value)
};
oneEntity = this._db.GetCollection(typeof(T).Name).FindOneAs<T>(args);
this._db.GetCollection(typeof(T).Name).FindAs<T>(Query.GTE(Field, Value)).ToList();
}
catch (Exception ex)
{
}
return oneEntity;
}
/// <summary>
/// 查询多条数据
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="Field">查询属性字段</param>
/// <param name="Value">字段值</param>
/// <returns>返回当前实体集合</returns>
public List<T> FindMore<T>(string Field, string Value)
{
List<T> list = new List<T>();
try
{
list = this._db.GetCollection(typeof(T).Name).FindAs<T>(Query.GTE(Field, Value)).ToList();
}
catch (Exception ex)
{
}
return list;
}
/// <summary>
/// 查询文档所有数据
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public List<T> FindAllMore<T>()
{
List<T> list = new List<T>();
try
{
list = this._db.GetCollection(typeof(T).Name).FindAllAs<T>().ToList();
}
catch (Exception ex)
{
}
return list;
}
/// <summary>
/// 分页查询文档
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="pageIndex">页次</param>
/// <param name="pageRow">每页显示记录数</param>
/// <param name="total">总记录数</param>
/// <returns></returns>
public List<T> FindMoreForPage<T>(int pageIndex, int pageRow, ref long total)
{
List<T> list = new List<T>();
try
{
total = this._db.GetCollection(typeof(T).Name).FindAllAs<T>().Count(); //获取总记录数
if (pageIndex == 1)
{
list = this._db.GetCollection(typeof(T).Name).FindAllAs<T>().SetLimit(pageRow).ToList();
}
else
{
var bd = this._db.GetCollection(typeof(T).Name).FindAll().SetSortOrder("_id:1").SetLimit((pageIndex - 1) * pageRow).Last(); //获取最后一个ID主键
var el = bd.GetElement(0);
var value = el.Value;
list = this._db.GetCollection(typeof(T).Name).FindAs<T>(Query.GT("_id", value)).SetSortOrder("_id:1").SetLimit(pageRow).ToList();
}
}
catch (Exception ex)
{
}
return list;
}
/// <summary>
/// by 2020 ADD
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="query">查询条件</param>
/// <param name="pageIndex">当前页</param>
/// <param name="rows">行数</param>
/// <param name="totalCount">总行数</param>
/// <returns></returns>
public List<T> FindPageNewAdd<T>(IMongoQuery query, int pageIndex, int rows, ref long totalCount)
{
List<T> list = new List<T>();
int skipCount = 0;
try
{
if (pageIndex > 1)
{
skipCount = (pageIndex - 1) * rows;
}
else
{
pageIndex = 1;
}
totalCount = this._db.GetCollection(typeof(T).Name).FindAs<T>(query).Count();
if (totalCount > 0)
{
list = this._db.GetCollection(typeof(T).Name).FindAs<T>(query).SetFlags(QueryFlags.NoCursorTimeout).SetSortOrder().SetSkip(skipCount).SetLimit(rows).ToList();
}
}
catch (Exception)
{
throw;
}
return list;
}
/// <summary>
/// 按条件分页查询
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="query">查询条件</param>
/// <param name="pageIndex">页次</param>
/// <param name="pageRow">每页显示记录数</param>
/// <param name="total">总记录数</param>
/// <returns></returns>
public List<T> FindMoreForPageByCondion<T>(IMongoQuery query, int pageIndex, int pageRow, ref long total)
{
List<T> list = new List<T>();
try
{
total = this._db.GetCollection(typeof(T).Name).FindAs<T>(query).Count();//获取总记录数
if (pageIndex == 1)
{
list = this._db.GetCollection(typeof(T).Name).FindAs<T>(query).SetSortOrder(SortBy.Descending("CreateDate")).SetLimit(pageRow).ToList();
}
else
{
var bd = this._db.GetCollection(typeof(T).Name).Find(query).SetSortOrder("_id:1").SetLimit((pageIndex - 1) * pageRow).Last(); //获取最后一个ID主键
var el = bd.GetElement(0);
var value = el.Value;
list = this._db.GetCollection(typeof(T).Name).FindAs<T>(query).SetSortOrder("_id:1").SetSkip(pageRow).SetLimit(pageRow).ToList();
}
}
catch (Exception ex)
{
}
return list;
}
/// <summary>
/// 更新实体单个字段值
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="whereField">条件字段</param>
/// <param name="whereValue">条件字段值</param>
/// <param name="updateField">修改字段</param>
/// <param name="updateValue">修改字段值</param>
/// <returns></returns>
public bool UpdateEntity<T>(string whereField, string whereValue, string updateField, string updateValue)
{
bool isOk = true;
try
{
var query = Query.EQ(whereField, whereValue);
var update = Update.Set(updateField, updateValue);
WriteConcernResult result = this._db.GetCollection(typeof(T).Name).Update(query, update);
if (!result.Ok)
isOk = false;
}
catch (Exception ex)
{
}
return isOk;
}
/// <summary>
/// 更新整个实体模型字段
/// </summary>
/// <typeparam name="T">泛型参数</typeparam>
/// <param name="whereField">条件字段</param>
/// <param name="whereValue">条件值</param>
/// <param name="updateEntity">实体模型</param>
/// <returns>True:成功,False:失败</returns>
public bool UpdateEntityMoreFields<T>(string whereField, string whereValue, T updateEntity)
{
bool isOk = true;
try
{
var query = Query.EQ(whereField, whereValue);
BsonDocument bsonDoc = updateEntity.ToBsonDocument(typeof(T));
var update = new UpdateDocument{
{"$set",bsonDoc}
};
WriteConcernResult result = this._db.GetCollection(typeof(T).Name).Update(query, update);
if (!result.Ok)
isOk = false;
}
catch (Exception ex)
{
}
return isOk;
}
/// <summary>
/// 删除实体文档
/// </summary>
/// <typeparam name="T">泛型参数</typeparam>
/// <param name="whereField">条件字段</param>
/// <param name="whereValue">条件值</param>
/// <returns></returns>
public bool DelEntity<T>(string whereField, string whereValue)
{
bool isOk = true;
try
{
var query = Query.EQ(whereField, whereValue);
WriteConcernResult result = this._db.GetCollection(typeof(T).Name).Remove(query);
if (!result.Ok)
isOk = false;
}
catch (Exception ex)
{
}
return isOk;
}
#endregion
#region GridFS 文件操作
/// <summary>
///
/// </summary>
/// <returns></returns>
public MongoCursor<MongoGridFSFileInfo> FindAll()
{
return this._db.GetGridFS(MongoGridFSSettings.Defaults).FindAll();
}
/// <summary>
///
/// </summary>
/// <param name="filePath"></param>
public void UploadFile(string filePath)
{
FileInfo fi = new FileInfo(filePath);
this._db.GetGridFS(MongoGridFSSettings.Defaults).Upload(filePath, fi.Name);
}
/// <summary>
///
/// </summary>
/// <param name="filePath"></param>
/// <param name="fileName"></param>
public void UploadFile(string filePath, string fileName)
{
this._db.GetGridFS(MongoGridFSSettings.Defaults).Upload(filePath, fileName);
}
/// <summary>
///下载文件保存到默认目录
/// </summary>
/// <param name="fileName"></param>
/// <param name="filePath"></param>
public void DownloadFile(string fileName)
{
this._db.GetGridFS(MongoGridFSSettings.Defaults).Download(fileName);
}
/// <summary>
///下载文件保存到其他目录
/// </summary>
/// <param name="fileName"></param>
/// <param name="filePath"></param>
public void DownloadFileOther(string localFileName, string remoteFileName)
{
this._db.GetGridFS(MongoGridFSSettings.Defaults).Download(localFileName,remoteFileName);
}
/// <summary>
///
/// </summary>
/// <param name="fileName"></param>
public void DeleteFile(string fileName)
{
this._db.GetGridFS(MongoGridFSSettings.Defaults).Delete(fileName);
}
/// <summary>
///
/// </summary>
public void DeleteAll()
{
foreach (var inst in this._db.GetGridFS(MongoGridFSSettings.Defaults).FindAll())
{
inst.Delete();
}
}
#endregion
}
}
3、创建实体 User.cs
using MongoDB.Bson;
namespace MongoHelper.Model
{
public class User
{
public ObjectId _id;
public string name { get; set; }
public int age { get; set; }
}
}
4、调用示例代码
var list = new List<User>();
for (int i = 0; i < 100; i++)
{
User user = new User();
user.age = 20 + i;
user.name = "测试" + i;
list.Add(user);
}
//新增实体
//tool.Add(list);
//更新实体
//tool.UpdateEntity<User>("name", "测试", "age", "99");
//删除操作
//tool.DelEntity<User>("name","测试");
long total = 0;
//构造查询条件
IMongoQuery query = Query.And(
Query.Matches("name", "1")
);
//分页查询数据
var ll = tool.FindMoreForPageByCondion<User>(query, 0, 10, ref total);
// 文件操作
var model = tool.FindAllMore<User>();
string folder = @"E:\photo";
DirectoryInfo di = new DirectoryInfo(folder);
//循环读取文件上传
foreach (var file in di.GetFiles())
{
tool.UploadFile(file.FullName, file.Name);
}
var fileModel = tool.FindAll().First();
// 保存文件指定目录
tool.DownloadFileOther("D:\\"+fileModel.Name, fileModel.Name);//下载文件到当前目录
pictureBox1.ImageLocation = "D:\\"+fileModel.Name;
具体的代码地址:https://gitee.com/hgm1989/mongodb-demo
如有问题可以随时沟通交流。
IT技术分享社区
个人博客网站:https://programmerblog.xyz
文章推荐程序员效率:画流程图常用的工具程序员效率:整理常用的在线笔记软件远程办公:常用的远程协助软件,你都知道吗?51单片机程序下载、ISP及串口基础知识硬件:断路器、接触器、继电器基础知识
作者:天使不哭
微信号:hgmyzhl
微信公众号:小明互联网技术分享社区
CSDN:IT技术分享社区
知乎:IT技术分享社区
出处:小明互联网技术分享社区
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.