Exemplo n.º 1
0
        /// <summary>
        /// 异步批量修改数据
        /// </summary>
        /// <param name="dic">要修改的字段</param>
        /// <param name="host">mongodb连接信息</param>
        /// <param name="filter">修改条件</param>
        /// <returns></returns>
        public static async Task <UpdateResult> UpdateManayAsync(MongodbHost host, Dictionary <string, string> dic, FilterDefinition <T> filter)
        {
            try
            {
                var client = MongodbClient <T> .MongodbInfoClient(host);

                T t = new T();
                //要修改的字段
                var list = new List <UpdateDefinition <T> >();
                foreach (var item in t.GetType().GetProperties())
                {
                    if (!dic.ContainsKey(item.Name))
                    {
                        continue;
                    }
                    var value = dic[item.Name];
                    list.Add(Builders <T> .Update.Set(item.Name, value));
                }
                var updatefilter = Builders <T> .Update.Combine(list);

                return(await client.UpdateManyAsync(filter, updatefilter));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// 异步根据id查询一条数据
        /// </summary>
        /// <param name="host">mongodb连接信息</param>
        /// <param name="id">objectid</param>
        /// <returns></returns>
        public static async Task <T> FindOneAsync(MongodbHost host, string id, string[] field = null)
        {
            try
            {
                var client = MongodbClient <T> .MongodbInfoClient(host);

                FilterDefinition <T> filter = Builders <T> .Filter.Eq("_id", new ObjectId(id));

                //不指定查询字段
                if (field == null || field.Length == 0)
                {
                    return(await client.Find(filter).FirstOrDefaultAsync());
                }

                //制定查询字段
                var fieldList = new List <ProjectionDefinition <T> >();
                for (int i = 0; i < field.Length; i++)
                {
                    fieldList.Add(Builders <T> .Projection.Include(field[i].ToString()));
                }
                var projection = Builders <T> .Projection.Combine(fieldList);

                fieldList?.Clear();
                return(await client.Find(filter).Project <T>(projection).FirstOrDefaultAsync());
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// 修改一条信息
        /// </summary>
        /// <param name="mongodbHost"></param>
        /// <returns></returns>
        public string UpdUserMsg(MongodbHost mongodbHost)
        {
            //根据条件查询集合
            var list = new List <FilterDefinition <Bar> >
            {
                //Builders<Bar>.Filter.Lte("counter", 9),
                Builders <Bar> .Filter.Lt("Count", 20)
            };
            var filter = Builders <Bar> .Filter.And(list);

            //2.查询字段
            var field = new[] { "Name", "Count", "Counter", "Type", "Info" };
            //3.排序字段
            var sort = Builders <Bar> .Sort.Descending("Count");

            //List<Bar> res =  MongoDbHelper<Bar>.FindList(mongodbHost, filter, field, sort);
            var res = MongoDbHelper <Bar> .FindListAsync(mongodbHost, filter, field, sort);

            Bar bar = res.Result.First();

            bar.Type = "admin222";
            var ress = MongoDbHelper <Bar> .UpdateAsync(mongodbHost, bar, bar.Id.ToString());

            Console.WriteLine(ress.Id);
            Console.WriteLine(ress.Result.UpsertedId);
            Console.WriteLine(ress.Result.MatchedCount);
            Console.WriteLine(res.Result.ToJson());
            return("Success");
        }
Exemplo n.º 4
0
        /// <summary>
        /// 查询 表信息   异步
        /// </summary>
        /// <param name="mongodbHost"></param>
        /// <returns></returns>
        public string SelUserMsg(MongodbHost mongodbHost)
        {
            //根据条件查询集合
            var list = new List <FilterDefinition <Bar> >
            {
                //Builders<Bar>.Filter.Lte("counter", 9),
                Builders <Bar> .Filter.Lt("Count", 20)
            };
            var filter = Builders <Bar> .Filter.And(list);

            //2.查询字段
            var field = new[] { "Name", "Count", "Counter", "Type", "Info" };
            //3.排序字段
            var sort = Builders <Bar> .Sort.Descending("Count");

            //List<Bar> res =  MongoDbHelper<Bar>.FindList(mongodbHost, filter, field, sort);
            var res = MongoDbHelper <Bar> .FindListAsync(mongodbHost, filter, field, sort);

            Console.WriteLine(res.Result.Count);
            Console.WriteLine(res.Result.First().Name);
            Console.WriteLine(res.Id);
            Console.WriteLine(res.Result.First().Info.X);
            Console.WriteLine(res.Result.ToArray().ToJson());
            return("Success");
        }
Exemplo n.º 5
0
        /// <summary>
        /// 异步修改一条数据
        /// </summary>
        /// <param name="t">添加的实体</param>
        /// <param name="host">mongodb连接信息</param>
        /// <returns></returns>
        public static async Task <UpdateResult> UpdateAsync(MongodbHost host, T t, string id)
        {
            try
            {
                var client = MongodbClient <T> .MongodbInfoClient(host);

                //修改条件
                FilterDefinition <T> filter = Builders <T> .Filter.Eq("_id", new ObjectId(id));

                //要修改的字段
                var list = new List <UpdateDefinition <T> >();
                foreach (var item in t.GetType().GetProperties())
                {
                    if (item.Name.ToLower() == "id")
                    {
                        continue;
                    }
                    list.Add(Builders <T> .Update.Set(item.Name, item.GetValue(t)));
                }
                var updatefilter = Builders <T> .Update.Combine(list);

                return(await client.UpdateOneAsync(filter, updatefilter));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// 获取mongodb实例
        /// </summary>
        /// <param name="host">连接字符串,库,表</param>
        /// <returns></returns>
        public static IMongoCollection <T> MongodbInfoClient(MongodbHost host)
        {
            MongoClient client   = new MongoClient(host.Connection);
            var         dataBase = client.GetDatabase(host.DataBase);

            return(dataBase.GetCollection <T>(host.Table));
        }
Exemplo n.º 7
0
        /// <summary>
        /// 异步根据条件获取总数
        /// </summary>
        /// <param name="host">mongodb连接信息</param>
        /// <param name="filter">条件</param>
        /// <returns></returns>
        public static async Task <long> CountAsync(MongodbHost host, FilterDefinition <T> filter)
        {
            try
            {
                var client = MongodbClient <T> .MongodbInfoClient(host);

                return(await client.CountAsync(filter));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 8
0
        /// <summary>
        /// 根据条件获取总数
        /// </summary>
        /// <param name="host">mongodb连接信息</param>
        /// <param name="filter">条件</param>
        /// <returns></returns>
        public static long Count(MongodbHost host, FilterDefinition <T> filter)
        {
            try
            {
                var client = MongodbClient <T> .MongodbInfoClient(host);

                return(client.Count(filter));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 9
0
        /// <summary>
        /// 异步删除多条数据
        /// </summary>
        /// <param name="host">mongodb连接信息</param>
        /// <param name="filter">删除的条件</param>
        /// <returns></returns>
        public static async Task <DeleteResult> DeleteManyAsync(MongodbHost host, FilterDefinition <T> filter)
        {
            try
            {
                var client = MongodbClient <T> .MongodbInfoClient(host);

                return(await client.DeleteManyAsync(filter));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// 删除一条数据
        /// </summary>
        /// <param name="host">mongodb连接信息</param>
        /// <param name="filter">删除的条件</param>
        /// <returns></returns>
        public static DeleteResult DeleteMany(MongodbHost host, FilterDefinition <T> filter)
        {
            try
            {
                var client = MongodbClient <T> .MongodbInfoClient(host);

                return(client.DeleteMany(filter));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// 批量插入
        /// </summary>
        /// <param name="host">mongodb连接信息</param>
        /// <param name="t">实体集合</param>
        /// <returns></returns>
        public static int InsertMany(MongodbHost host, List <T> t)
        {
            try
            {
                var client = MongodbClient <T> .MongodbInfoClient(host);

                client.InsertMany(t);
                return(1);
            }
            catch (Exception)
            {
                return(0);
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// 添加一条数据
        /// </summary>
        /// <param name="t">添加的实体</param>
        /// <param name="host">mongodb连接信息</param>
        /// <returns></returns>
        public static int Add(MongodbHost host, T t)
        {
            try
            {
                var client = MongodbClient <T> .MongodbInfoClient(host);

                client.InsertOne(t);
                return(1);
            }
            catch
            {
                return(0);
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// 异步批量插入
        /// </summary>
        /// <param name="host">mongodb连接信息</param>
        /// <param name="t">实体集合</param>
        /// <returns></returns>
        public static async Task <int> InsertManyAsync(MongodbHost host, List <T> t)
        {
            try
            {
                var client = MongodbClient <T> .MongodbInfoClient(host);

                await client.InsertManyAsync(t);

                return(1);
            }
            catch
            {
                return(0);
            }
        }
Exemplo n.º 14
0
        /// <summary>
        /// 删除一条数据
        /// </summary>
        /// <param name="host">mongodb连接信息</param>
        /// <param name="id">objectId</param>
        /// <returns></returns>
        public static DeleteResult Delete(MongodbHost host, string id)
        {
            try
            {
                var client = MongodbClient <T> .MongodbInfoClient(host);

                FilterDefinition <T> filter = Builders <T> .Filter.Eq("_id", new ObjectId(id));

                return(client.DeleteOne(filter));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// 异步删除一条数据
        /// </summary>
        /// <param name="host">mongodb连接信息</param>
        /// <param name="id">objectId</param>
        /// <returns></returns>
        public static async Task <DeleteResult> DeleteAsync(MongodbHost host, string id)
        {
            try
            {
                var client = MongodbClient <T> .MongodbInfoClient(host);

                //修改条件
                FilterDefinition <T> filter = Builders <T> .Filter.Eq("_id", new ObjectId(id));

                return(await client.DeleteOneAsync(filter));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 16
0
        /// <summary>
        /// 分页查询集合
        /// </summary>
        /// <param name="host">mongodb连接信息</param>
        /// <param name="filter">查询条件</param>
        /// <param name="pageIndex">当前页</param>
        /// <param name="pageSize">页容量</param>
        /// <param name="count">总条数</param>
        /// <param name="field">要查询的字段,不写时查询全部</param>
        /// <param name="sort">要排序的字段</param>
        /// <returns></returns>
        public static List <T> FindListByPage(MongodbHost host, FilterDefinition <T> filter, int pageIndex, int pageSize, out long count, string[] field = null, SortDefinition <T> sort = null)
        {
            try
            {
                var client = MongodbClient <T> .MongodbInfoClient(host);

                count = client.Count(filter);
                //不指定查询字段
                if (field == null || field.Length == 0)
                {
                    if (sort == null)
                    {
                        return(client.Find(filter).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToList());
                    }
                    //进行排序
                    return(client.Find(filter).Sort(sort).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToList());
                }

                //制定查询字段
                var fieldList = new List <ProjectionDefinition <T> >();
                for (int i = 0; i < field.Length; i++)
                {
                    fieldList.Add(Builders <T> .Projection.Include(field[i].ToString()));
                }
                var projection = Builders <T> .Projection.Combine(fieldList);

                fieldList?.Clear();

                //不排序
                if (sort == null)
                {
                    return(client.Find(filter).Project <T>(projection).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToList());
                }

                //排序查询
                return(client.Find(filter).Sort(sort).Project <T>(projection).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToList());
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 17
0
        /// <summary>
        /// 异步查询集合
        /// </summary>
        /// <param name="host">mongodb连接信息</param>
        /// <param name="filter">查询条件</param>
        /// <param name="field">要查询的字段,不写时查询全部</param>
        /// <param name="sort">要排序的字段</param>
        /// <returns></returns>
        public static async Task <List <T> > FindListAsync(MongodbHost host, FilterDefinition <T> filter, string[] field = null, SortDefinition <T> sort = null)
        {
            try
            {
                var client = MongodbClient <T> .MongodbInfoClient(host);

                //不指定查询字段
                if (field == null || field.Length == 0)
                {
                    if (sort == null)
                    {
                        return(await client.Find(filter).ToListAsync());
                    }
                    return(await client.Find(filter).Sort(sort).ToListAsync());
                }

                //制定查询字段
                var fieldList = new List <ProjectionDefinition <T> >();
                for (int i = 0; i < field.Length; i++)
                {
                    fieldList.Add(Builders <T> .Projection.Include(field[i].ToString()));
                }
                var projection = Builders <T> .Projection.Combine(fieldList);

                fieldList?.Clear();
                if (sort == null)
                {
                    return(await client.Find(filter).Project <T>(projection).ToListAsync());
                }
                //排序查询
                return(await client.Find(filter).Sort(sort).Project <T>(projection).ToListAsync());
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 18
0
        static void Main(string[] args)
        {
            // MongoClient 连接
            //var client = new MongoClient("mongodb://192.168.1.172:27017");
            ////获取数据库
            //var database = client.GetDatabase("test");
            //// 获取集合
            //var collection = database.GetCollection<BsonDocument>("bar");
            MongodbHost mongodbHost = new MongodbHost
            {
                Connection = "mongodb://192.168.1.167:27017",
                DataBase   = "Test",
                Table      = "users"
            };

            Selcs selcs = new Selcs();

            selcs.UpdUserMsg(mongodbHost);

            //for (int i=5;i>0;i--) {
            //    Console.WriteLine(ObjectId.GenerateNewId());
            //}


            //int num = MongoDbHelper<Bar>.Add(mongodbHost, new Bar("zhangsan", "lisi", 34, new Info(111, 222)));
            //Console.WriteLine(num);

            //var list = new Bar
            //{
            //    Id = ObjectId.GenerateNewId(),
            //    Name = "zhangsan",
            //    Count = 22,
            //    Counter = 23,
            //    Type = "user",
            //    Info = new Info(22, 23)
            //};
            //var list1 = new Bar
            //{
            //    Id = ObjectId.GenerateNewId(),
            //    Name = "lisi",
            //    Count = 11,
            //    Counter = 33,
            //    Type = "teacher",
            //    Info = new Info(11, 33)
            //};
            //var list2 = new Bar
            //{
            //    Id = ObjectId.GenerateNewId(),
            //    Name = "wangwu",
            //    Count = 15,
            //    Counter = 25,
            //    Type = "user",
            //    Info = new Info(15, 25)
            //};
            //var list3 = new Bar
            //{
            //    Id = ObjectId.GenerateNewId(),
            //    Name = "zhaoliu",
            //    Count = 14,
            //    Counter = 53,
            //    Type = "user",
            //    Info = new Info(14, 53)
            //};
            //var list4 = new Bar
            //{
            //    Id = ObjectId.GenerateNewId(),
            //    Name = "chenqiq",
            //    Count = 23,
            //    Counter = 32,
            //    Type = "user",
            //    Info = new Info(23, 32)
            //};
            //List<Bar> documents = new List<Bar>
            //{
            //    list,list1,list2,list3,list4
            //};
            //int num = MongoDbHelper<Bar>.InsertMany(mongodbHost, documents);
            //Console.WriteLine(num);

            ////1.批量修改,修改的条件
            //var time = DateTime.Now;
            //var list = new List<FilterDefinition<Bar>>
            //{
            //    Builders<Bar>.Filter.Lte("counter", 9),
            //    Builders<Bar>.Filter.Gte("counter", 1)
            //};
            //var filter = Builders<Bar>.Filter.And(list);

            ////2.要修改的字段内容
            //var dic = new Dictionary<string, string>
            //{
            //    { "UseAge", "168" },
            //    { "Name", "朝阳" }
            //};
            ////3.批量修改
            //var kk = MongoDbHelper<Bar>.UpdateManay(mongodbHost, dic, filter);

            //Console.WriteLine(kk.IsAcknowledged);
            //Console.WriteLine(kk.IsModifiedCountAvailable);
            //Console.WriteLine(kk.MatchedCount);
            //Console.WriteLine(kk.ModifiedCount);


            ////根据条件查询集合
            //var list = new List<FilterDefinition<Bar>>
            //{
            //    //Builders<Bar>.Filter.Lte("counter", 9),
            //    Builders<Bar>.Filter.Lt("Count", 20)
            //};
            //var filter = Builders<Bar>.Filter.And(list);
            ////2.查询字段
            //var field = new[] { "Name", "Count", "Counter", "Type" ,"Info"};
            ////3.排序字段
            //var sort = Builders<Bar>.Sort.Descending("Count");
            //List<Bar> res = MongoDbHelper<Bar>.FindList(mongodbHost, filter, null, sort);
            //Console.WriteLine(res.Count);
            //Console.WriteLine(res.First().Info.X);
            //Console.WriteLine(res.ToArray().ToJson());


            ////分页查询,查询条件
            //var time = DateTime.Now;
            //var list = new List<FilterDefinition<PhoneEntity>>();
            //list.Add(Builders<PhoneEntity>.Filter.Lt("AddTime", time.AddDays(400)));
            //list.Add(Builders<PhoneEntity>.Filter.Gt("AddTime", time));
            //var filter = Builders<PhoneEntity>.Filter.And(list);
            //long count = 0;
            ////排序条件
            //var sort = Builders<PhoneEntity>.Sort.Descending("AddTime");
            //var res = TMongodbHelper<PhoneEntity>.FindListByPage(host, filter, 2, 10, out count, null, sort);

            Console.ReadKey();
        }