zoukankan      html  css  js  c++  java
  • C# Mongodb 封装类

    1.  依赖包 MongoDB.Driver; MongoDB.Json; MongoDB.Bson;

    2. 上代码

      1 using MongoDB.Driver;
      2 using System;
      3 using System.Collections.Generic;
      4 using System.Text;
      5 
      6 using System.Linq;
      7 using System.Linq.Expressions;
      8 using System.Reflection;
      9 using MongoDB.Driver.Linq;
     10 
     11 namespace Common
     12 {
     13 
     14 
     15     public class MongodbHelper
     16     {
     17         protected static MongoClient client;
     18 
     19         public MongodbHelper()
     20         {
     21             client = new MongoClient("mongodb://localhost:27017");
     22         }
     23         static MongodbHelper()
     24         {
     25             client = new MongoClient("mongodb://localhost:27017");
     26         }
     27         /// <summary>
     28         /// 获取 Collection 信息
     29         /// </summary>
     30         /// <typeparam name="T">实体类型</typeparam>
     31         /// <param name="collName">Collection 名称</param>
     32         /// <param name="dbName">DBase名称</param>
     33         /// <returns></returns>
     34         public static MyCollection<T> GetCollection<T>(string collName, string dbName)
     35         {
     36             MyCollection<T> mycollection = new MyCollection<T>();
     37             IMongoDatabase database = client.GetDatabase(dbName);
     38             IMongoCollection<T> collection = database.GetCollection<T>(collName);
     39             mycollection.collection = collection;
     40             return mycollection;
     41         }
     42     }
     43 
     44     public class MyCollection<T>
     45     {
     46         public IMongoCollection<T> collection;
     47 
     48         /// <summary>
     49         /// 查询数据 延迟加载 后期可以使用Linq  Lambda处理数据
     50         /// </summary>
     51         /// <returns></returns>
     52         public IMongoQueryable<T> QueryData()
     53         {
     54             var list = collection.AsQueryable<T>();
     55             return list;
     56         }
     57         /// <summary>
     58         /// 查询所有数据
     59         /// </summary>
     60         /// <param name="expression"></param>
     61         /// <returns></returns>
     62         public List<T> QueryData(Expression<Func<T, bool>> expression)
     63         {
     64             var list = collection.AsQueryable().Where(expression);
     65             return list.ToList<T>();
     66         }
     67 
     68         /// <summary>
     69         /// 分页查询
     70         /// </summary>
     71         /// <param name="expressio"></param>
     72         /// <param name="pageInfo"></param>
     73         /// <returns></returns>
     74         public PageInfo<T> QueryData(Expression<Func<T, bool>> expressio, PageInfo<T> pageInfo)
     75         {
     76             List<T> list = null;
     77             pageInfo.Totoal = collection.AsQueryable<T>().Count();
     78             pageInfo.PageNum = (int)Math.Ceiling(pageInfo.Totoal / pageInfo.PageSize * 0.1);
     79             if (pageInfo == null || pageInfo.IsAll == true)
     80                 if (expressio != null)
     81                     list = collection.AsQueryable<T>().Where(expressio).ToList();
     82                 else list = collection.AsQueryable<T>().ToList();
     83             else if (expressio != null)
     84             {
     85                 list = collection.AsQueryable<T>().Where(expressio).Skip(pageInfo.PageSize * (pageInfo.PageIndex - 1)).Take(pageInfo.PageSize).ToList();
     86             }
     87             else
     88             {
     89                 list = collection.AsQueryable<T>().Skip(pageInfo.PageSize * (pageInfo.PageIndex - 1)).Take(pageInfo.PageSize).ToList();
     90             }
     91             pageInfo.Data = list;
     92             return pageInfo;
     93         }
     94 
     95         /// <summary>
     96         /// 新增一条数据(文档)
     97         /// </summary>
     98         /// <param name="ts"></param>
     99         public void AddDoc(T ts)
    100         {
    101             collection.InsertOne(ts);
    102         }
    103         /// <summary>
    104         /// 批量新增多个文档
    105         /// </summary>
    106         /// <param name="ts"></param>
    107         public void AddDocs(List<T> ts)
    108         {
    109             collection.InsertMany(ts);
    110         }
    111         /// <summary>
    112         /// 更新文档  不存在就新增
    113         /// </summary>
    114         /// <param name="filter"></param>
    115         /// <param name="t"></param>
    116         public void UpdateDoc(Expression<Func<T, bool>> filter, T t)
    117         {
    118             // FilterDefinition<T> filter = null;
    119             //  UpdateDefinition<T> update = Builders<T>.Update.ToBsonDocument();//   null;// Builders<T>.Update.
    120             var newData = BuildQueryOption(t);
    121             UpdateResult result = collection.UpdateOne(filter, newData, new UpdateOptions { IsUpsert = true });
    122         }
    123         /// <summary>
    124         /// 删除文档   
    125         /// </summary>
    126         /// <param name="predicate"></param>
    127         public void Detele(Expression<Func<T, bool>> predicate)
    128         {
    129             var result = collection.DeleteMany(predicate);//.ConfigureAwait(false);
    130                                                           // return result.DeletedCount;
    131         }
    132         /// <summary>
    133         /// 利用反射创建 更新字段 (这里没有处理空)
    134         /// </summary>
    135         /// <param name="doc"></param>
    136         /// <returns></returns>
    137         private UpdateDefinition<T> BuildQueryOption(T doc)
    138         {
    139             var update = Builders<T>.Update;
    140             var updates = new List<UpdateDefinition<T>>();
    141 
    142             var t = doc.GetType();
    143             var proper = t.GetProperties();
    144             foreach (PropertyInfo info in proper)
    145             {
    146                 var value = info.GetValue(doc);
    147                 if (value != null)
    148                 {
    149                     updates.Add(update.Set(info.Name, info.GetValue(doc)));
    150                 }
    151 
    152             }
    153             // update.Combine(updates);
    154             return update.Combine(updates);
    155         }
    156     }
    157     /// <summary>
    158     /// 分页信息
    159     /// </summary>
    160     /// <typeparam name="T"></typeparam>
    161     public class PageInfo<T>
    162     {
    163         public bool IsAll { get; set; } = false;
    164         public int PageSize { get; set; } = 100;
    165         public int PageIndex { get; set; } = 1;
    166         public long Totoal { get; set; }
    167 
    168         public int PageNum { get; set; }
    169 
    170         public List<T> Data { get; set; }
    171     }
    172 }
    View Code

    3. 测试方法

    using Common;
    using System;
    using System.Collections.Generic;
    using System.Linq.Expressions;
    using System.Text;
    
    namespace ZhiHuHot
    {
        public class TestMongo
        {
    
            public void GetHot()
            {
                MyCollection<HotInfo> collection = MongodbHelper.GetCollection<HotInfo>("ZhiHuHot", "ZhiHu");
    
                Expression<Func<HotInfo, bool>> predicate = null;
    
                predicate = a => a.HotID.Equals(391481443);
    
                PageInfo<HotInfo> hots = collection.QueryData(null, new PageInfo<HotInfo>());
            }
        }
    }
    View Code
  • 相关阅读:
    枚举求解,也叫暴力破解
    多线程之线程的中止
    beginners with the Multithreading programming
    EditBox control Update Problem (A CString type EditBox control in a loop cannot be updated immidiately)
    有关多线程的一些技术问题
    多线程编程基础知识
    VC的若干实用小技巧 (如何干净的删除一个类)
    进入MFC讲坛的前 (Window 程序详细分析)
    Multithreading using MFC in Plain English: Part I
    关于在VS2005环境下无法从源视图切换到设计视图的解决方案
  • 原文地址:https://www.cnblogs.com/chengxun/p/12857662.html
Copyright © 2011-2022 走看看