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

1、引入NuGet包

img

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;
            }

        }
    }
}

3、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()

//删除学号 等于 20210001 的 2 个文档
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) 

4、使用代码

//得到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);

5、更多命令

MongoDB | 菜鸟教程 (runoob.com)

posted @ 2021-07-08 16:55  Journey&Flower  阅读(193)  评论(0)    收藏  举报