一步步操作mongoDB,增删改查,分页查询 C#
十年河东,十年河西,莫欺少年穷
学无止境,精益求精
传统的关系数据库一般由数据库(database)、表(table)、记录(record)三个层次概念组成,MongoDB是由数据库(database)、集合(collection)、文档对象(document)三个层次组成。MongoDB对于关系型数据库里的表,但是集合中没有列、行和关系概念,这体现了模式自由的特点。
那么在c#如何使用呢?下面看个例子,你会发现上手非常简单。
1、新建一个NetCore控制台应用程序
然后Nuget引用,如下:
Install-Package MongoDB.Driver -Version 2.11.0
Install-Package MongoDB.Bson -Version 2.11.0
然后,新建一个MongoDb的操作类【此操作类用于创建数据库、表,批量插入,查询全部数据等】
using MongoDB.Driver; using System; using System.Collections.Generic; using System.Text; namespace ConsoleMongoDb.Helper { /// <summary> /// 这里的T 代表数据表的Model /// </summary> /// <typeparam name="T"></typeparam> public class MongoHelper<T> { public readonly IMongoCollection<T> MongoTb; public MongoHelper(DatabaseSettings settings) { var client = new MongoClient(settings.ConnectionString); var database = client.GetDatabase(settings.DatabaseName); MongoTb = database.GetCollection<T>(settings.LogsCollectionName); } /// <summary> /// 单条插入 /// </summary> /// <param name="book"></param> /// <returns></returns> public T Create(T book) { MongoTb.InsertOne(book); return book; } /// <summary> /// 批量插入 /// </summary> /// <param name="books"></param> /// <returns></returns> public List<T> Create(List<T> books) { MongoTb.InsertMany(books); return books; } /// <summary> /// 批量查询所有 /// </summary> /// <returns></returns> public List<T> Get() { return MongoTb.Find(book => true).ToList(); } } public class DatabaseSettings { public string LogsCollectionName { get; set; } = "TableName";//日志 public string ConnectionString { get; set; } = "mongodb://127.0.0.1:27017";//连接字符串 public string DatabaseName { get; set; } = "DbName"; } }
在上述的操作类中,由注释可知,<T> 代表mongoDB的表对象,那么下面我们创建一张mongoDB的表对象【学生表】,如下:
using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; using System; using System.Collections.Generic; using System.Text; namespace ConsoleMongoDb.MongoModel { /// <summary> /// mongoDb数据表实体 /// </summary> public class Student { [BsonId] [BsonRepresentation(BsonType.ObjectId)] public string Id { get; set; } [BsonElement("StudentName")] public string StudentName { get; set; } public string StudentSex { get; set; } public DateTime CreateDate { get; set; } } }
为了演示大数据,我们引入一个随机生成姓名的类,如下:
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using System.Web; namespace ConsoleMongoDb.Helper { public class connonName { private object O = new object(); public static List<string> Xing = new List<string>() {"赵", "钱", "孙", "李", "周", "吴", "郑", "王", "冯", "陈", "楮", "卫", "蒋", "沈", "韩", "杨", "朱", "秦", "尤", "许", "何", "吕", "施", "张", "孔", "曹", "严", "华", "金", "魏", "陶", "姜", "戚", "谢", "邹", "喻", "柏", "水", "窦", "章", "云", "苏", "潘", "葛", "奚", "范", "彭", "郎", "鲁", "韦", "昌", "马", "苗", "凤", "花", "方", "俞", "任", "袁", "柳", "酆", "鲍", "史", "唐", "费", "廉", "岑", "薛", "雷", "贺", "倪", "汤", "滕", "殷", "罗", "毕", "郝", "邬", "安", "常", "乐", "于", "时", "傅", "皮", "卞", "齐", "康", "伍", "余", "元", "卜", "顾", "孟", "平", "黄", "和", "穆", "萧", "尹", "姚", "邵", "湛", "汪", "祁", "毛", "禹", "狄", "米", "贝", "明", "臧", "计", "伏", "成", "戴", "谈", "宋", "茅", "庞", "熊", "纪", "舒", "屈", "项", "祝", "董", "梁", "杜", "阮", "蓝", "闽", "席", "季", "麻", "强", "贾", "路", "娄", "危", "江", "童", "颜", "郭", "梅", "盛", "林", "***", "锺", "徐", "丘", "骆", "高", "夏", "蔡", "田", "樊", "胡", "凌", "霍", "虞", "万", "支", "柯", "昝", "管", "卢", "莫", "经", "房", "裘", "缪", "干", "解", "应", "宗", "丁", "宣", "贲", "邓", "郁", "单", "杭", "洪", "包", "诸", "左", "石", "崔", "吉", "钮", "龚", "程", "嵇", "邢", "滑", "裴", "陆", "荣", "翁", "荀", "羊", "於", "惠", "甄", "麹", "家", "封", "芮", "羿", "储", "靳", "汲", "邴", "糜", "松", "井", "段", "富", "巫", "乌", "焦", "巴", "弓", "牧", "隗", "山", "谷", "车", "侯", "宓", "蓬", "全", "郗", "班", "仰", "秋", "仲", "伊", "宫", "宁", "仇", "栾", "暴", "甘", "斜", "厉", "戎", "祖", "武", "符", "刘", "景", "詹", "束", "龙", "叶", "幸", "司", "韶", "郜", "黎", "蓟", "薄", "印", "宿", "白", "怀", "蒲", "邰", "从", "鄂", "索", "咸", "籍", "赖", "卓", "蔺", "屠", "蒙", "池", "乔", "阴", "郁", "胥", "能", "苍", "双", "闻", "莘", "党", "翟", "谭", "贡", "劳", "逄", "姬", "申", "扶", "堵", "冉", "宰", "郦", "雍", "郤", "璩", "桑", "桂", "濮", "牛", "寿", "通", "边", "扈", "燕", "冀", "郏", "浦", "尚", "农", "温", "别", "庄", "晏", "柴", "瞿", "阎", "充", "慕", "连", "茹", "习", "宦", "艾", "鱼", "容", "向", "古", "易", "慎", "戈", "廖", "庾", "终", "暨", "居", "衡", "步", "都", "耿", "满", "弘", "匡", "国", "文", "寇", "广", "禄", "阙", "东", "欧", "殳", "沃", "利", "蔚", "越", "夔", "隆", "师", "巩", "厍", "聂", "晁", "勾", "敖", "融", "冷", "訾", "辛", "阚", "那", "简", "饶", "空", "曾", "毋", "沙", "乜", "养", "鞠", "须", "丰", "巢", "关", "蒯", "相", "查", "后", "荆", "红", "游", "竺", "权", "逑", "盖", "益", "桓", "公", "仉", "督", "晋", "楚", "阎", "法", "汝", "鄢", "涂", "钦", "岳", "帅", "缑", "亢", "况", "后", "有", "琴", "归", "海", "墨", "哈", "谯", "笪", "年", "爱", "阳", "佟", "商", "牟", "佘", "佴", "伯", "赏", "万俟", "司马", "上官", "欧阳", "夏侯", "诸葛", "闻人", "东方", "赫连", "皇甫", "尉迟", "公羊", "澹台", "公冶", "宗政", "濮阳", "淳于", "单于", "太叔", "申屠", "公孙", "仲孙", "轩辕", "令狐", "锺离", "宇文", "长孙", "慕容", "鲜于", "闾丘", "司徒", "司空", "丌官", "司寇", "子车", "微生", "颛孙", "端木", "巫马", "公西", "漆雕", "乐正", "壤驷", "公良", "拓拔", "夹谷", "宰父", "谷梁", "段干", "百里", "东郭", "南门", "呼延", "羊舌", "梁丘", "左丘", "东门", "西门", "南宫"}; static string _lastNameMan = "刚伟勇毅俊峰强军平保东文辉力明永健世广志义兴良海山仁波宁贵福生龙元全国胜学祥才发武新利清飞彬富顺信子杰涛昌成康星光天达安岩中茂进林有坚和彪博诚先敬震振壮会思群豪心邦承乐绍功松善厚庆磊民友裕河哲江超浩亮政谦亨奇固之轮翰朗伯宏言若鸣朋斌梁栋维启克伦翔旭鹏泽晨辰士以建家致树炎德行时泰盛雄琛钧冠策腾楠榕风航弘"; static string _lastNameWoMan = "秀娟英华慧巧美娜静淑惠珠翠雅芝玉萍红娥玲芬芳燕彩春菊兰凤洁梅琳素云莲真环雪荣爱妹霞香月莺媛艳瑞凡佳嘉琼勤珍贞莉桂娣叶璧璐娅琦晶妍茜秋珊莎锦黛青倩婷姣婉娴瑾颖露瑶怡婵雁蓓纨仪荷丹蓉眉君琴蕊薇菁梦岚苑婕馨瑗琰韵融园艺咏卿聪澜纯毓悦昭冰爽琬茗羽希宁欣飘育滢馥筠柔竹霭凝鱼晓欢霄枫芸菲寒伊亚宜可姬舒影荔枝思丽墨"; public static List<string> GetManName() { Stopwatch sw = new Stopwatch(); sw.Start(); List<string> NameArray = new List<string>(); int XingLen = Xing.Count;//501个姓 char[] ManChar = _lastNameMan.ToCharArray();//151的男士名 char[] WoManChar = _lastNameWoMan.ToCharArray();//151个女士名 int ManNameLen = ManChar.Length;//151的男士名 int WoManNameLen = WoManChar.Length;//151个女士名 // foreach (var item in Xing) { foreach (var Ming in ManChar) { NameArray.Add(item + Ming); } } foreach (var item in Xing) { foreach (var Ming in WoManChar) { NameArray.Add(item + Ming); } } sw.Stop(); TimeSpan ts2 = sw.Elapsed; Console.WriteLine("Parallel.ForEach总共花费{0}ms.", ts2.TotalMilliseconds); return NameArray; } } }
然后客户端方法为:
using ConsoleMongoDb.Helper; using ConsoleMongoDb.MongoModel; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ConsoleMongoDb { class Program { /// <summary> /// mongoDb会自动判断数据库、数据表是否存在,如果不存在,则创建 /// </summary> /// <param name="args"></param> static void Main(string[] args) { Console.WriteLine("现在开始创建数据库,数据表,并插入大量数据"); //创建一个StudentDb数据库,并指定一张待建的表Student,采用默认连接方式,如果不同,请修改 DatabaseSettings ds = new DatabaseSettings() { DatabaseName = "StudentDb",//数据库名 LogsCollectionName = "Student"//表名 }; MongoHelper<Student> mongo = new MongoHelper<Student>(ds); List<string> NameArray = connonName.GetManName(); List<Student> Lst = new List<Student>(); for (int i=0;i< NameArray.Count; i++) { var student = new Student() { StudentName = NameArray[i], CreateDate = DateTime.Now, StudentSex = (i % 2 == 0 ? "男" : "女") }; Lst.Add(student); } //批量插入mongodb mongo.Create(Lst); Console.WriteLine("插入数据完毕"); Console.Read(); } } }
事实证明:
mongoDb果然不是盖的,通过上述的程序,一共插入了十几万条数据,总花费大概不到二秒钟,牛逼吧。
那么,现在我们有了这么十几万条数据,我们就可以安心的进行分页处理了,那么mongodb中分页怎么搞呢?
首先创建基本的分页类
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleMongoDb.Helper { public static class MongoPaginationService { /// <summary> /// 分页 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="entitys"></param> /// <param name="json"></param> /// <param name="pagination"></param> /// <returns></returns> public static IQueryable<T> BasePager<T>(this IOrderedQueryable<T> entitys, ref BasePaginationModel pagination) { if (pagination != null) { var result = entitys.GetBasePagination(pagination); return result; } return null; } /// <summary> /// 获取分页后的数据 /// </summary> /// <typeparam name="T">实体类型</typeparam> /// <param name="source">数据源IQueryable</param> /// <param name="pagination">分页参数</param> /// <returns></returns> private static IQueryable<T> GetBasePagination<T>(this IOrderedQueryable<T> source, BasePaginationModel pagination) { pagination.Total = source.Count(); return source.Skip((pagination.PageNumber - 1) * pagination.PageSize).Take(pagination.PageSize); } } public class PaginationListModel<T> { public PaginationListModel() { Data = new List<T>(); } public List<T> Data { get; set; } public BasePaginationModel Pagination { get; set; } } public class PaginationModel { #region 构造函数 public PaginationModel() { PageNumber = 1; PageSize = 10; } #endregion /// <summary> /// 当前页码 /// </summary> public int PageNumber { get; set; } /// <summary> /// 每页行数 /// </summary> public int PageSize { get; set; } } /// <summary> /// 基本分页实体类 /// </summary> public class BasePaginationModel { #region 构造函数 public BasePaginationModel() { PageNumber = 1; PageSize = 10; } #endregion #region 成员 /// <summary> /// 总页数 /// </summary> public int PageCount { get { int pages = Total / PageSize; int pageCount = Total % PageSize == 0 ? pages : pages + 1; return pageCount; } } /// <summary> /// 当前页码 /// </summary> public int PageNumber { get; set; } /// <summary> /// 每页行数 /// </summary> public int PageSize { get; set; } /// <summary> /// 总记录数 /// </summary> public int Total { get; set; } /// <summary> /// 总页数 /// </summary> public int Pages { get => PageCount; } /// <summary> /// 是否首页 /// </summary> public bool IsFirstPage { get => PageNumber == 1; } /// <summary> /// 是否尾页 /// </summary> public bool IsLastPage { get => PageNumber == Pages; } #endregion } }
然后我的分页方法为:
static PaginationListModel<Student> GetPagination(DatabaseSettings settings,ref BasePaginationModel Pagination) { var client = new MongoClient(settings.ConnectionString); var database = client.GetDatabase(settings.DatabaseName); var Mongo = database.GetCollection<Student>(settings.LogsCollectionName); var mongorResult = Mongo.AsQueryable<Student>().Where(A => !string.IsNullOrEmpty(A.StudentName)).OrderByDescending(item => item.CreateDate); var result = MongoPaginationService.BasePager<Student>(mongorResult, ref Pagination); PaginationListModel<Student> M = new PaginationListModel<Student>() { Data = result.ToList(), Pagination = Pagination }; return M; }
客户端代码为:
/// <summary> /// mongoDb会自动判断数据库、数据表是否存在,如果不存在,则创建 /// </summary> /// <param name="args"></param> static void Main(string[] args) { Console.WriteLine("现在开始创建数据库,数据表,并插入大量数据"); //创建一个StudentDb数据库,并指定一张待建的表Student,采用默认连接方式,如果不同,请修改 DatabaseSettings ds = new DatabaseSettings() { DatabaseName = "StudentDb",//数据库名 LogsCollectionName = "Student"//表名 }; MongoHelper<Student> mongo = new MongoHelper<Student>(ds); List<string> NameArray = connonName.GetManName(); List<Student> Lst = new List<Student>(); for (int i=0;i< NameArray.Count; i++) { var student = new Student() { StudentName = NameArray[i], CreateDate = DateTime.Now, StudentSex = (i % 2 == 0 ? "男" : "女") }; Lst.Add(student); } //批量插入mongodb mongo.Create(Lst); Console.WriteLine("插入数据完毕"); //查询并分页 BasePaginationModel pagination = new BasePaginationModel() { PageNumber = 1, PageSize = 100 }; var RT = GetPagination(ds, ref pagination); Console.WriteLine("当前页码为1,也容量为100,总共有" + RT.Pagination.Total + "条数据,总共分了" + RT.Pagination.PageCount + "页。"); Console.WriteLine("查询结果为:"); foreach(var item in RT.Data) { Console.WriteLine("学生:" + item.StudentName); } Console.Read(); }
OK,我们看下输出的结果:
可以看到,总共30多万条数据,分了3027页,每页100条数据【每运行一次,就会插入十几万条数据,因此,目前是30多万条数据】。
以上便是我的分页。
扩展:
如何删除数据表数据库呢?
static void Main(string[] args) { DatabaseSettings ds = new DatabaseSettings() { DatabaseName = "StudentDb",//数据库名 LogsCollectionName = "Student"//表名 }; //执行删除数据库操作 var client = new MongoClient(ds.ConnectionString); var database = client.GetDatabase(ds.DatabaseName); database.DropCollection("Student");//删除数据表 Console.WriteLine("学生表删除成功"); database.Client.DropDatabase("StudentDb"); Console.WriteLine("数据库删除成功"); Console.Read(); }
OK,就这么多吧。
关于多条件关联查询,MongoDb有自己的一套东东,反正用起来不是那么友好...
如下:
/// <summary> /// 查询MongoDb 电柜门状态 带有分页 /// </summary> /// <returns></returns> public BaseResponse<PaginationListModel<LogsForcloud181DgTb>> QueryDoorStatus(QueryDoorStatusModel data, ref BasePaginationModel Pagination) { string DbName = "LogstoreDb" + "_" + data.SDate.ToString("yyyyMMdd"); LogstoreDatabaseSettings settings = new LogstoreDatabaseSettings() { LogsCollectionName = CommEnum.MongoDbnameEnm.DevicePortStatus.ToString(), DatabaseName = DbName }; var client = new MongoClient(settings.ConnectionString); var database = client.GetDatabase(settings.DatabaseName); var Mongo = database.GetCollection<LogsForcloud181DgTb>(settings.LogsCollectionName); //IAsyncCursor<LogsForcloud181DgTb> Tb = null; List<FilterDefinition<LogsForcloud181DgTb>> SearchList=new List<FilterDefinition<LogsForcloud181DgTb>>(); var builder = Builders<LogsForcloud181DgTb>.Filter; if (!string.IsNullOrEmpty(data.deviceNum)) { //等于 var filter = builder.Eq("deviceNum", data.deviceNum); SearchList.Add(filter); //Tb = Mongo.Find<LogsForcloud181DgTb>(filter).ToCursor(); } if (data.BeginDate.HasValue) { var bDate = Convert.ToDateTime(data.BeginDate).AddHours(-8); //约束条件 DateTime startTime = new DateTime(bDate.Year, bDate.Month, bDate.Day, bDate.Hour, bDate.Minute, bDate.Second, DateTimeKind.Utc); //大于等于 var filter = builder.Gte("CreateTime", startTime); SearchList.Add(filter); } if (data.EndDate.HasValue) { var eDate = Convert.ToDateTime(data.EndDate).AddHours(-8); //约束条件 DateTime endTime = new DateTime(eDate.Year, eDate.Month, eDate.Day, eDate.Hour, eDate.Minute, eDate.Second, DateTimeKind.Utc); //小于等于 var filter = builder.Lte("CreateTime", endTime); SearchList.Add(filter); } var MongoR = Mongo.Find(Builders<LogsForcloud181DgTb>.Filter.And(SearchList)).ToList(); var mongorResult = MongoR.AsQueryable<LogsForcloud181DgTb>().Where(A => A.deviceNum == data.deviceNum).OrderByDescending(item => item.CreateTime); ; var result = MongoPaginationService.BasePager<LogsForcloud181DgTb>(mongorResult, ref Pagination); PaginationListModel<LogsForcloud181DgTb> M = new PaginationListModel<LogsForcloud181DgTb>() { Data = result.ToList(), Pagination = Pagination }; return CommonBaseResponse.SetResponse<PaginationListModel<LogsForcloud181DgTb>>(M, true); }
MongoDB更新如下:
private static object oo = new object(); /// <summary> /// 设备的固定上传信息--.仓位状态上报--30秒心跳包 /// </summary> /// <param name="data"></param> public void devicePingToCloudToDb(string data) { lock (oo) { var model = Newtonsoft.Json.JsonConvert.DeserializeObject<WA_RequestBase<List<WA_CangweiZtResult>>>(data); if (model.dat != null && model.dat.Count > 0) { LogstoreDatabaseSettings st = new LogstoreDatabaseSettings() { LogsCollectionName = "WA_" + CommEnum.MongoDbnameEnm.DevicePortStatus.ToString() }; var Model = new WA_DevicePortStatusTodb { CreateTime = DateTime.Now, cmd = model.cmd, deviceNum = model.id, dr = model.dat[0].dr, ds = model.dat[0].ds, btinfo = model.dat[0].btinfo, dt = model.dat[0].dt, //data = data }; if (!string.IsNullOrEmpty(Model.btinfo)) { btinfoModel TbModel = new btinfoModel(Model.btinfo); // Model.batteryType = 0; Model.voltage = TbModel.Voltage; Model.scale = TbModel.SOC; Model.capacity = TbModel.Caption; Model.batterySN = TbModel.BettaryNum; Model.TotalVoltage = TbModel.TotalVoltage; Model.Electric = TbModel.Electric; Model.BettaryStatus = TbModel.BettaryStatus; Model.BettaryStatusString = TbModel.BettaryStatusString; Model.MOS = TbModel.MOS; Model.MOSEjz = TbModel.MOSEjz; Model.MOSEjzString = TbModel.MOSEjzString; Model.ljfdrl = TbModel.ljfdrl; Model.ljcdrl = TbModel.ljcdrl; Model.softVersion = TbModel.softVersion; Model.heardWareVersion = TbModel.heardWareVersion; Model.MaxSigVoltage = TbModel.MaxSigVoltage; Model.MinSigVoltage = TbModel.MinSigVoltage; Model.MaxTemperature = TbModel.MaxTemperature; Model.MinTemperature = TbModel.MinTemperature; Model.VoltageNum = TbModel.VoltageNum; Model.SigVoltage = TbModel.SigVoltage; Model.TemperatureNum = TbModel.TemperatureNum; Model.SigTemperature = TbModel.SigTemperature; Model.Mos_1 = TbModel.Mos_1; Model.Mos_2 = TbModel.Mos_2; Model.Police = TbModel.Police; Model.PoliceEjz = TbModel.PoliceEjz; Model.PoliceEjzString = TbModel.PoliceEjzString; Model.ljqcbcs = TbModel.ljqcbcs; Model.ljcdcs = TbModel.ljcdcs; Model.cdqcdcs = TbModel.cdqcdcs; Model.dgcdcs = TbModel.dgcdcs; Model.ggStatus = TbModel.ggStatus; // } new MongoLogService<WA_DevicePortStatusTodb>(st).Create(Model); //上为插入,下为更新 //存在则更新 不存在,则插入 LogstoreDatabaseSettings st_now = new LogstoreDatabaseSettings() { LogsCollectionName = "WA_" + CommEnum.MongoDbnameEnm.DevicePortNowStatus.ToString() }; var client = new MongoClient(st_now.ConnectionString); var database = client.GetDatabase(st_now.DatabaseName); var Mongo = database.GetCollection<WA_DeviceNowStatusTodb>(st_now.LogsCollectionName); var builder = Builders<WA_DeviceNowStatusTodb>.Filter; var filter = builder.And(builder.Eq("deviceNum", Model.deviceNum), builder.Eq("dr", Model.dr)); var MongoEntity = Mongo.Find(filter).FirstOrDefault(); if (MongoEntity == null) { var Model2 = new WA_DeviceNowStatusTodb { CreateTime = DateTime.Now, cmd = model.cmd, deviceNum = model.id, dr = model.dat[0].dr, ds = model.dat[0].ds, dt = model.dat[0].dt, }; if (!string.IsNullOrEmpty(Model.btinfo)) { btinfoModel TbModel = new btinfoModel(Model.btinfo); Model2.batteryType = 0; Model2.voltage = TbModel.Voltage; Model2.scale = TbModel.SOC; Model2.capacity = TbModel.Caption; Model2.batterySN = TbModel.BettaryNum; Model2.TotalVoltage = TbModel.TotalVoltage; Model2.Electric = TbModel.Electric; Model2.BettaryStatus = TbModel.BettaryStatus; Model2.BettaryStatusString = TbModel.BettaryStatusString; } new MongoLogService<WA_DeviceNowStatusTodb>(st_now).Create(Model2); } else { if (!string.IsNullOrEmpty(Model.btinfo)) { var update = Builders<WA_DeviceNowStatusTodb>.Update.Set("deviceNum", Model.deviceNum).Set("dr", Model.dr).Set("ds", Model.ds).Set("dt", Model.dt).Set("batteryType", Model.batteryType).Set("voltage", Model.voltage).Set("scale", Model.scale).Set("capacity", Model.capacity).Set("batterySN", Model.batterySN).Set("TotalVoltage", Model.TotalVoltage).Set("Electric", Model.Electric).Set("BettaryStatus", Model.BettaryStatus).Set("BettaryStatusString", Model.BettaryStatusString).Set("CreateTime", Model.CreateTime); Mongo.UpdateMany(filter, update); } } } } //30秒心跳更新 新增到数据库 //Task.Run(delegate { DevicePortStatusToSql(model);}); }
主要代码:
//存在则更新 不存在,则插入 LogstoreDatabaseSettings st_now = new LogstoreDatabaseSettings() { LogsCollectionName = "WA_" + CommEnum.MongoDbnameEnm.DevicePortNowStatus.ToString() }; var client = new MongoClient(st_now.ConnectionString); var database = client.GetDatabase(st_now.DatabaseName); var Mongo = database.GetCollection<WA_DeviceNowStatusTodb>(st_now.LogsCollectionName); var builder = Builders<WA_DeviceNowStatusTodb>.Filter; var filter = builder.And(builder.Eq("deviceNum", Model.deviceNum), builder.Eq("dr", Model.dr)); var MongoEntity = Mongo.Find(filter).FirstOrDefault(); if (MongoEntity == null) { var Model2 = new WA_DeviceNowStatusTodb { CreateTime = DateTime.Now, cmd = model.cmd, deviceNum = model.id, dr = model.dat[0].dr, ds = model.dat[0].ds, dt = model.dat[0].dt, }; if (!string.IsNullOrEmpty(Model.btinfo)) { btinfoModel TbModel = new btinfoModel(Model.btinfo); Model2.batteryType = 0; Model2.voltage = TbModel.Voltage; Model2.scale = TbModel.SOC; Model2.capacity = TbModel.Caption; Model2.batterySN = TbModel.BettaryNum; Model2.TotalVoltage = TbModel.TotalVoltage; Model2.Electric = TbModel.Electric; Model2.BettaryStatus = TbModel.BettaryStatus; Model2.BettaryStatusString = TbModel.BettaryStatusString; } new MongoLogService<WA_DeviceNowStatusTodb>(st_now).Create(Model2); } else { if (!string.IsNullOrEmpty(Model.btinfo)) { var update = Builders<WA_DeviceNowStatusTodb>.Update.Set("deviceNum", Model.deviceNum).Set("dr", Model.dr).Set("ds", Model.ds).Set("dt", Model.dt).Set("batteryType", Model.batteryType).Set("voltage", Model.voltage).Set("scale", Model.scale).Set("capacity", Model.capacity).Set("batterySN", Model.batterySN).Set("TotalVoltage", Model.TotalVoltage).Set("Electric", Model.Electric).Set("BettaryStatus", Model.BettaryStatus).Set("BettaryStatusString", Model.BettaryStatusString).Set("CreateTime", Model.CreateTime); Mongo.UpdateMany(filter, update); } }
查询:
4.查询
4.1 查询部门是开发部的信息
//创建约束生成器 FilterDefinitionBuilder<BsonDocument> builderFilter = Builders<BsonDocument>.Filter; //约束条件 FilterDefinition<BsonDocument> filter = builder.Eq("DepartmentName", "开发部"); //获取数据 var result = coll.Find<BsonDocument>(filter).ToList(); foreach (var item in result) { //取出整条值 Console.WriteLine(item.AsBsonValue); }
4.2 获取Sum大于4的数据
//创建约束生成器 FilterDefinitionBuilder<BsonDocument> builderFIlter = Builders<BsonDocument>.Filter; //约束条件 FilterDefinition<BsonDocument> filter = builder.Gt("Sum", 4); var result = coll.Find<BsonDocument>(filter).ToList(); foreach (var item in result) { //取出整条值 Console.WriteLine(item.AsBsonValue); }
4.3 And约束
//创建约束生成器 FilterDefinitionBuilder<BsonDocument> builderFilter = Builders<BsonDocument>.Filter; //约束条件 FilterDefinition<BsonDocument> filter = builder.And(builder.Gt("Sum", "2"), builder.Eq("DepartmentName", "运维")); var result = coll.Find<BsonDocument>(filter).ToList(); foreach (var item in result) { //取出整条值 Console.WriteLine(item.AsBsonValue); }
4.4查询指定值
//创建约束生成器 FilterDefinitionBuilder<BsonDocument> builderFilter = Builders<BsonDocument>.Filter;
ProjectionDefinitionBuilder<BsonDocument> builderProjection = Builders<BsonDocument>.Projection; //Include 包含某元素 Exclude 不包含某元素 ProjectionDefinition<BsonDocument> projection = builderProjection.Include("DepartmentName").Exclude("_id"); var result = coll.Find<BsonDocument>(builderFilter.Empty).Project(projection).ToList(); foreach (var item in result) { //取出整条值 Console.WriteLine(item.AsBsonValue); }
4.5 排序
//创建生成器 FilterDefinitionBuilder<BsonDocument> builderFilter = Builders<BsonDocument>.Filter; //排序生成器 SortDefinitionBuilder<BsonDocument> builderSort = Builders<BsonDocument>.Sort; //排序约束 Ascending 正序 Descending 倒序 SortDefinition<BsonDocument> sort = builderSort.Ascending("Sum"); var result = coll.Find<BsonDocument>(builderFilter.Empty).Sort(sort).ToList(); foreach (var item in result) { //取出整条值 Console.WriteLine(item.AsBsonValue); }
4.6 In查询
//创建生成器 FilterDefinitionBuilder<BsonDocument> builderFilter = Builders<BsonDocument>.Filter; FilterDefinition<BsonDocument> filter = builderFilter.In("DepartmentName", new[] { "测试部", "开发部" }); var result = coll.Find<BsonDocument>(filter).ToList(); foreach (var item in result) { //取出整条值 Console.WriteLine(item.AsBsonValue); }
4.7 分页查询
//创建生成器 FilterDefinitionBuilder<BsonDocument> builderFilter = Builders<BsonDocument>.Filter; //分页 Skip 跳过 Limit查询多少 var result = coll.Find<BsonDocument>(builderFilter.Empty).Skip(1).Limit(1).ToList(); foreach (var item in result) { //取出整条值 Console.WriteLine(item.AsBsonValue); }
4.8查询总条目数
//创建生成器 FilterDefinitionBuilder<BsonDocument> builderFilter = Builders<BsonDocument>.Filter; //总条目数 var result = coll.Find<BsonDocument>(builderFilter.Empty).Count();
4.9Linq查询
//创建生成器//linq var result = from y in coll.AsQueryable() select new { DepartmentName = y["DepartmentName"], id = y["_id"] }; foreach (var item in result) { Console.WriteLine("DepartmentName:" + item.DepartmentName + "====Id:"+item.id); }
4.10分组查询
//创建生成器 FilterDefinitionBuilder<BsonDocument> builderFilter = Builders<BsonDocument>.Filter; //分组 var result = from y in coll.AsQueryable() group y by y["DepartmentName"] into s select new { DepartmentName = s.Key, Count = s.Count() }; foreach (var item in result) { Console.WriteLine("DepartmentName:" + item.DepartmentName + "====Count:"+item.Count); }
4.11连表查询
//linq //连表查询 在这里是自己连自己 var result = from u in coll.AsQueryable() join o in coll.AsQueryable() on u["_id"] equals o["_id"] select new { DepartmentName1 = u["DepartmentName"], DepartmentName2 = u["DepartmentName"] }; foreach (var item in result) { Console.WriteLine("DepartmentName1:" + item.DepartmentName1 + "====DepartmentName2:" + item.DepartmentName2); }
删除单条数据
public BaseResponse RemoveBatteryOtaSoftWareInfo(RemoveOtaSoftWareInfoModel data) { LogstoreDatabaseSettings settings = new LogstoreDatabaseSettings() { LogsCollectionName = CommEnum.BatteryOtaEnm.OtaBatterySoftWareInfo.ToString(), DatabaseName = DatabaseName }; var client = new MongoClient(settings.ConnectionString); var database = client.GetDatabase(DatabaseName); var Mongo = database.GetCollection<OtaSoftWareInfoTb>(settings.LogsCollectionName); var builder = Builders<OtaSoftWareInfoTb>.Filter; if (string.IsNullOrEmpty(data.Id)) { return CommonBaseResponse.SetResponse(false, "请求ID不能为空。"); } else { } var filter = builder.Eq("Id", data.Id); Mongo.DeleteOne(filter); return CommonBaseResponse.SetResponse(true ); }
/// <summary> /// 清除所有表 OTA记录 测试数据 /// </summary> /// <returns></returns> public async Task<BaseResponse> ClearOtaRecords() { LogstoreDatabaseSettings settings = new LogstoreDatabaseSettings() { LogsCollectionName = CommEnum.BatteryOtaEnm.OtaBatteryReveiceCompletePack.ToString(), DatabaseName = DatabaseName }; var client = new MongoClient(settings.ConnectionString); var database = client.GetDatabase(DatabaseName); await database.DropCollectionAsync(BatteryOtaEnm.OtaBatteryHeartPack.ToString()); await database.DropCollectionAsync(BatteryOtaEnm.OtaBatteryReveiceCompletePack.ToString()); await database.DropCollectionAsync(BatteryOtaEnm.OtaBatteryReveiceShakeHandPack.ToString()); await database.DropCollectionAsync(BatteryOtaEnm.OtaBatteryReveiceSigPack.ToString()); await database.DropCollectionAsync(BatteryOtaEnm.OtaBatterySendCompletePack.ToString()); await database.DropCollectionAsync(BatteryOtaEnm.OtaBatterySendShakeHandPack.ToString()); await database.DropCollectionAsync(BatteryOtaEnm.OtaBatterySendSigPack.ToString()); return CommonBaseResponse.SetResponse(true); }
@天才卧龙的博客