弯道超车-MongoDB基本使用

MongoDB基本使用

一、介绍: 本文主要是介绍基于.net core使用MongoDB

二、相关代码

1. 基本使用

 var mongodbString = "mongodb://zero:123456@192.168.52.88:27017/admin";
            {
                //与Mongodb建立连接
                var client = new MongoClient(mongodbString);
                System.Console.WriteLine(client);
                //获得数据库,没有则自动创建
                IMongoDatabase db = client.GetDatabase("app");
                //拿到集合(表)
                IMongoCollection<Student> student = db.GetCollection<Student>("Student");
                var data = new Student();
                data.id = 6;
                data.name = "tomcat";
                data.age = 24;
                data.remarks = "no data";
                //添加一条数据
                student.InsertOne(data);

                // //拿到集合(表)
                IMongoCollection<School> school = db.GetCollection<School>("School");
                var data1 = new School();
                data1.name = "beijing";
                data1.address = "xxxxxx";
                //添加一条数据
                school.InsertOne(data1);
            }

2. 封装并且使用

public class DBbase<T> where T : class, new()
    {
        MongoClient client;
        IMongoDatabase database;
        public IMongoCollection<T> collection;
        public DBbase()
        {
            //var client = new MongoClient("mongodb://host:27017,host2:27017/?replicaSet=rs0");
            client = new MongoClient("mongodb://39.96.34.52:27017");
            database = client.GetDatabase("test");
            Type type = typeof(T);
            collection = database.GetCollection<T>(type.Name.ToLower());
        }

        public void DropDatabase()
        {
            client.DropDatabase("test");
        }
        public void InsertOne(T model)
        {
            collection.InsertOne(model);
        }
        public void InsertMany(params T[] modes)
        {
            collection.InsertMany(modes);
        }
        public IMongoQueryable<T> Select()
        {
            return collection.AsQueryable<T>();
        }
        public IMongoQueryable<T> Select(int pageIndex, int pageSize)
        {
            return collection.AsQueryable<T>().Skip(pageSize * (pageIndex - 1)).Take(pageSize);
        }
        public IMongoQueryable<T> Select(Expression<Func<T, bool>> predicate, Expression<Func<T, object>> keySelector, int pageIndex, int pageSize)
        {
            return collection.AsQueryable<T>().Where(predicate).OrderBy(keySelector).Skip(pageSize * (pageIndex - 1)).Take(pageSize);
        }
        public void UpdateMany(Expression<Func<T, bool>> filter, UpdateDefinition<T> update)
        {
            collection.UpdateMany(filter, update);
        }

        public void UpdateOne(Expression<Func<T, bool>> filter, T update)
        {
            collection.ReplaceOne(filter, update);
        }

        public void DeleteMany(Expression<Func<T, bool>> filter)
        {
            collection.DeleteMany(filter);
        }

    }

使用

public class LinqOperation
    {
        static DBbase<Userinfo> dBbase = new DBbase<Userinfo>();

        public static void DropDatabase()
        {
            dBbase.DropDatabase();
        }
        public static void InserOne()
        {


            dBbase.InsertOne(new Userinfo()
            {
                Id = Guid.NewGuid().ToString(),
                Name = "诸葛亮",
                Address = "蜀国",
                Age = 27,
                Sex = "",
                DetpInfo = new DetpInfo()
                {
                    DeptId = 1,
                    DeptName = "蜀国集团"
                }
            });
            dBbase.InsertOne(new Userinfo()
            {
                Id = Guid.NewGuid().ToString(),
                Name = "荀彧",
                Address = "魏国",
                Age = 47,
                Sex = "",
                DetpInfo = new DetpInfo()
                {
                    DeptId = 2,
                    DeptName = "魏国集团"
                }
            });
            Console.WriteLine("写入完成");
        }

        public static void InsertMany()
        {

            var zhouyu = new Userinfo()
            {
                Id = Guid.NewGuid().ToString(),
                Name = "周瑜",
                Address = "吴国",
                Age = 32,
                Sex = "",
                DetpInfo = new DetpInfo() { DeptId = 3, DeptName = "吴国集团" }
            };
            var daqiao = new Userinfo()
            {
                Id = Guid.NewGuid().ToString(),
                Name = "大乔",
                Address = "吴国",
                Age = 14,
                Sex = "",
                DetpInfo = new DetpInfo() { DeptId = 3, DeptName = "吴国集团" }
            };
            var caocao = new Userinfo()
            {
                Id = Guid.NewGuid().ToString(),
                Name = "曹操",
                Address = "魏国",
                Age = 32,
                Sex = "",
                DetpInfo = new DetpInfo() { DeptId = 3, DeptName = "魏国集团" }
            };
            dBbase.InsertMany(zhouyu, daqiao, caocao);
            Console.WriteLine("批量写入完成");
        }

        public static void GetPage()
        {

            var pagelist = dBbase.Select(m => m.Sex == "", m => m.Age, 2, 2);
            foreach (var item in pagelist)
            {
                Console.WriteLine(item.Name + ":" + item.Age);
            }

            var query = from p in dBbase.collection.AsQueryable()
                        where (p.Sex == "") && p.Age > 18
                        select p;
            foreach (var item in query)
            {
                Console.WriteLine(item.Name + ":" + item.Age);
            }
        }

        public static void Update()
        {
            var daqiaod = dBbase.Select().Where(m => m.Name == "大乔").FirstOrDefault();
            daqiaod.Age = 18;
            dBbase.UpdateOne(m => m.Id == daqiaod.Id, daqiaod);
            Console.WriteLine("修改完成");
        }
        public static void DeleteMany()
        {
            dBbase.DeleteMany(m => m.Name == "大乔");
            Console.WriteLine("删除完成");
            //全部删除
            dBbase.DeleteMany(m => 1 == 1);
            Console.WriteLine("全部删除完成");


        }
        public static void GroupBy()
        {

            //linq  
            var groups = dBbase.collection.AsQueryable().GroupBy(m => new { m.DetpInfo.DeptId, m.DetpInfo.DeptName }).Select(t => new
            {
                DeptId = t.Key.DeptId,
                DeptName = t.Key.DeptName,
                number = t.Count(),
                ages = t.Sum(s => s.Age)
            }).Take(0).Skip(10);
            foreach (var item in groups)
            {
                Console.WriteLine(item.DeptName + ":" + item.number + ":" + item.ages);
            }
        }
    }

 

谢谢学习!!!关于Mongodb详细的介绍,请看我另外一篇文章

posted @ 2021-10-04 00:02  锦大大的博客呀!  阅读(24)  评论(0编辑  收藏  举报