Talk Is Cheap!!!✨|

Journey&Flower

园龄:7年3个月粉丝:40关注:121

MongoDB数据库之daonet的连接和使用

1、引入NuGet包

 2、数据库连接访问类

复制代码
using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Linq.Expressions;

namespace WebApi.Mongodb
{
    public class MongoDBHelper
    {
        /// <summary>
        /// MongoDb帮助类
        /// </summary>
        public class DB
        {
            private static readonly string connStr = ConfigurationManager.ConnectionStrings["mongodb"].ConnectionString;//"mongodb://127.0.0.1:27017";

            private static readonly string dbName = ConfigurationManager.ConnectionStrings["mongoDbName"].ConnectionString;//"schoolDB"

            private static IMongoDatabase db = null;

            private static readonly object lockHelper = new object();

            private DB() { }

            public static IMongoDatabase GetSQLMongodbInstance()
            {
                if (db == null)
                {
                    lock (lockHelper)
                    {
                        if (db == null)
                        {
                            var client = new MongoClient(connStr);
                            db = client.GetDatabase(dbName);
                        }
                    }
                }
                return db;
            }
        }

        public class MongoDbHelper<T>
        {
            private IMongoDatabase db = null;

            private IMongoCollection<T> collection = null;

            public MongoDbHelper()
            {
                this.db = DB.GetSQLMongodbInstance();
                collection = db.GetCollection<T>(typeof(T).Name);
            }
            /// <summary>
            /// 新增
            /// </summary>
            /// <param name="entity"></param>
            /// <returns></returns>
            public T Insert(T entity)
            {
                var flag = ObjectId.GenerateNewId();
                entity.GetType().GetProperty("_id").SetValue(entity, flag);
                collection.InsertOneAsync(entity);
                return entity;
            }

            /// <summary>
            /// 修改一个值
            /// </summary>
            /// <param name="express"></param>
            /// <param name="field"></param>
            /// <param name="value"></param>
            public bool Modify(Expression<Func<T, bool>> express, object updateField)
            {
                if (updateField == null) return false;

                var props = updateField.GetType().GetProperties();
                var field = props[0].Name;
                var value = props[0].GetValue(updateField);
                var updated = Builders<T>.Update.Set(field, value);

                UpdateResult result = collection.UpdateOneAsync(express, updated).Result;
                return result.ModifiedCount > 0 ? true : false;
            }

            /// <summary>
            /// 更新
            /// </summary>
            /// <param name="entity"></param>
            public bool Update(Expression<Func<T, bool>> express, T entity)
            {
                try
                {
                    var old = collection.Find(express).ToList().FirstOrDefault();

                    foreach (var prop in entity.GetType().GetProperties())
                    {
                        if (!prop.Name.Equals("_id"))
                        {
                            var newValue = prop.GetValue(entity);
                            var oldValue = old.GetType().GetProperty(prop.Name).GetValue(old);

                            if (newValue != null)
                            {
                                if (oldValue == null)
                                    oldValue = "";
                                if (!newValue.ToString().Equals(oldValue.ToString()))
                                {
                                    old.GetType().GetProperty(prop.Name).SetValue(old, newValue.ToString());
                                }
                            }
                        }
                    }

                    // var filter = Builders<T>.Filter.Eq("Id", entity.Id);
                    ReplaceOneResult result = collection.ReplaceOneAsync(express, old).Result;
                    if (result.ModifiedCount > 0)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                catch (Exception ex)
                {
                    var aaa = ex.Message + ex.StackTrace;
                    throw;
                }
            }

            /// <summary>
            /// 删除
            /// </summary>
            /// <param name="entity"></param>
            public bool Delete(Expression<Func<T, bool>> express)
            {
                DeleteResult result = collection.DeleteOneAsync(express).Result;
                return result.DeletedCount > 0 ? true : false;
            }

            /// <summary>
            /// 查询条件查询数据
            /// </summary>
            /// <returns></returns>
            public List<T> QueryAll(Expression<Func<T, bool>> express)
            {
                return collection.Find(express).ToList();
            }

            /// <summary>
            /// 根据条件查询一条数据
            /// </summary>
            /// <param name="express"></param>
            /// <returns></returns>
            public T QueryByFirst(Expression<Func<T, bool>> express)
            {
                return collection.Find(express).ToList().FirstOrDefault();
            }

            /// <summary>
            /// 批量添加
            /// </summary>
            /// <param name="list"></param>
            public void InsertBatch(List<T> list)
            {
                collection.InsertManyAsync(list);
            }

            /// <summary>
            /// 根据Id批量删除
            /// </summary>
            public bool DeleteBatch(List<ObjectId> list)
            {
                var filter = Builders<T>.Filter.In("_id", list);
                DeleteResult result = collection.DeleteManyAsync(filter).Result;
                return result.DeletedCount > 0 ? true : false;
            }

        }
    }
}
复制代码

4、Mongodb中的 增、删、查、改 命令

复制代码
//创建默认集合 无集合属性 无集合文档数据
db.createCollection("Student")

//创建固定集合 mycol,整个集合空间大小 6142800 B, 文档最大个数为 10000 个
db.createCollection("Student", {
    capped: true,
    autoIndexId: true,
    size: 
    6142800,
    max: 10000
})

//创建集合 Student 并插入 学员信息文挡   没有集合时会自动创建,有集合时会直接插入文档
db.Student.insert([{
    "姓名": "张三",
    "学号": "20210001",
    "性别": "男",
    "年龄": 21,
    "身高": 180,
    "专业": "待选",
    "入学日期": "2021-04-25"
    "创建时间": ISODate("2021-04-25T16:22:00+0800")
}])

//查询集合中的数据
db.Student.find()

//删除集合
db.Student.drop()

//插入文档
db.Student.insert([{
    "姓名": "李四",
    "学号": "20210002",
    "性别": "男",
    "年龄": 21,
    "身高": 180,
    "专业": "待选",
    "入学日期": "2021-04-25",
    "创建时间": ISODate("2021-04-25T16:22:00+0800")
}]);

//查询数据
db.Student.find()

//查询集合中数据总行数
db.Student.count()

//根据姓名更新 学生的数据 
db.Student.update({
    '姓名': '张三'
}, {
    $set: {
        '性别': '',
        '年龄': 18
    }
}, {
    upsert: false, //可选,这个参数的意思是,如果不存在update的记录,是否插入objNew,true为插入,默认是false,不插入
    
}, {
    multi: true//可选,mongodb 默认是false,只更新找到的第一条记录,如果这个参数为true,就把按条件查出来多条记录全部更新 和 upsert 参数 2选1
})

db.Student.find()

//删除学号 等于 20210001 的所有文档
db.Student.remove({
    '学号': '20210001'
})

db.Student.find()

//删除学号 等于 202100012 个文档
db.Student.remove({
    '学号': '20210001'
}, 2)

//删除集合下全部文档:
db.Student.deleteMany({})
//删除 学号 等于 20210001 的全部文档: db.Student.deleteMany({ "学号": "20210001" })
//删除 学号 等于 20210001 的一个文档: db.Student.deleteOne({ "学号": "20210001" }) db.Student.find() //命令行中运行 find().pretty() 查询结果格式更美观 db.Student.find().pretty() //非常重要的一点,如果查询集合时没有明确的时间属性,要倒序查询,或者取最新的时间,最好时用 _id 数据,这个属性由系统生成,包含时间特性 db.getCollection("Student").find().sort({ _id: - 1 }).limit(100).skip(0)
复制代码

 

 5、使用代码

//得到Mongodb数据库帮助类对象
IMongoDatabase mongoDB = MongoDBHelper.DB.GetSQLMongodbInstance();
//执行查询命令  在没有时间属性的文档中,用集合中的 _id 来替代时间排序非常重要
List<Student> list = mongoDB.GetCollection<Student>("Student").Find("{ $and : [{\"创建时间\" : { $gte : \"" + DateTime.Now.AddDays(-7).ToString("yyyy-MM-dd HH:mm") + " }}, {\"创建时间\" : { $lte : \"" + DateTime.Now.ToString("yyyy-MM-dd HH:mm") + " }}]}").SortByDescending(t => t._id).Limit(10).Skip(0);

6、更多命令

MongoDB | 菜鸟教程 (runoob.com)

本文作者:Journey&Flower

本文链接:https://www.cnblogs.com/JourneyOfFlower/p/14981815.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   Journey&Flower  阅读(183)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起
  1. 1 404 Not Found REOL
  2. 2 白色恋人 游鸿明
  3. 3 盛夏的果实 莫文蔚
  4. 4 以父之名 周杰伦
  5. 5 晴天 周杰伦
  6. 6 简单爱 周杰伦
  7. 7 东风破 周杰伦
  8. 8 稻香 周杰伦
  9. 9 爱在西元前 周杰伦
  10. 10 千里之外 费玉清-周杰伦
  11. 11 偏爱 张芸京
  12. 12 大海 张雨生
  13. 13 月亮惹的祸 张宇
  14. 14 雨一直下 张宇
  15. 15 过火 张信哲
  16. 16 隐形的翅膀 张韶涵
  17. 17 天下 张杰
  18. 18 当你孤单你会想起谁 张栋梁
  19. 19 清明雨上 许嵩
  20. 20 玫瑰花的葬礼 许嵩
  21. 21 断桥残雪 许嵩
  22. 22 城府 许嵩
  23. 23 等一分钟 徐誉滕
  24. 24 客官不可以 徐良_小凌
  25. 25 坏女孩 徐良_小凌
  26. 26 犯贱 徐良
  27. 27 菠萝菠萝蜜 谢娜
  28. 28 贝多芬的悲伤 萧风
  29. 29 睫毛弯弯 王心凌
  30. 30 我不是黄蓉 王蓉
  31. 31 秋天不回来 王强
  32. 32 今天你要嫁给我 陶喆,蔡依林
  33. 33 丁香花 唐磊
  34. 34 绿光 孙燕姿
  35. 35 求佛 誓言
  36. 36 十一年 邱永传
  37. 37 下辈子如果我还记得你 马郁
  38. 38 一千年以后 林俊杰
  39. 39 江南 林俊杰
  40. 40 曹操 林俊杰
  41. 41 背对背拥抱 林俊杰
  42. 42 会呼吸的痛 梁静茹
  43. 43 勇气 梁静茹
  44. 44 爱你不是两三天 梁静茹
  45. 45 红日 李克勤
  46. 46 星月神话 金莎
  47. 47 嘻唰唰 花儿乐队
  48. 48 穷开心 花儿乐队
  49. 49 六月的雨-《仙剑奇侠传》电视剧插曲 胡歌
  50. 50 一个人的寂寞两个人的错 贺一航
  51. 51 好想好想-《情深深雨濛濛》电视剧片尾曲 古巨基
  52. 52 情人 刀郎
  53. 53 冲动的惩罚 刀郎
  54. 54 西海情歌 刀郎
  55. 55 2002年的第一场雪 刀郎
  56. 56 红玫瑰 陈奕迅
  57. 57 浮夸 陈奕迅
  58. 58 爱情转移 陈奕迅
  59. 59 独家记忆 陈小春
  60. 60 记事本 陈慧琳
  61. 61 看我72变 蔡依林
  62. 62 寂寞在唱歌 阿桑
  63. 63 樱花草 Sweety
  64. 64 中国话 S.H.E
  65. 65 波斯猫 S.H.E
  66. 66 杀破狼-《仙剑奇侠传》电视剧片头曲 JS
  67. 67 Lydia F.I.R.
  68. 68 I Miss You 罗百吉_青春美少女.
白色恋人 - 游鸿明
00:00 / 00:00
An audio error has occurred, player will skip forward in 2 seconds.

作词 : 林利南

作曲 : 游鸿明

编曲 : 涂惠源

冷空气 却清晰

你在南极冰山雪地里

极光中雪白的肌肤

是哀愁是美丽

为了要遇见你

我连呼吸都反复练习

兰伯特仁慈的冰川

带领我走向你

零下九十一度的酷寒

滚滚红尘千年的呼喊

藏在沃斯托克的湖岸

沉寂轻叹

撒哈拉漫天狂沙 金字塔谁能解答

兵马俑谁与争锋 长城万里相逢

人世间悲欢聚散 一页页写在心上

含着泪白色恋人 却有灰色的年轮

零下九十一度的酷寒

滚滚红尘千年的呼喊

藏在沃斯托克的湖岸

沉静轻叹

撒哈拉漫天狂沙 金字塔谁能解答

兵马俑谁与争锋 长城万里相逢

人世间悲欢聚散 一页页写在心上

含着泪白色恋人 却有灰色的年轮

撒哈拉漫天狂沙 金字塔谁能解答

兵马俑谁与争锋 长城万里相逢

人世间悲欢聚散 一页页写在心上

含着泪白色恋人 却有灰色的年轮