zoukankan      html  css  js  c++  java
  • 【MongoDB学习-在.NET中的简单操作类】

    1.新建MVC项目, 管理NuGet包,进入下载MongDB.net库文件

    2.新增项目DAL数据访问层,引用以下库文件:

    3.C# 访问MongoDB通用方法类:

    [csharp] view plain copy
     
     print?
    1. using MongoDB.Driver;  
    2. using System;  
    3.   
    4. namespace DAL  
    5. {  
    6.     public class MongoDb  
    7.     {  
    8.         public MongoDb(string host,string timeOut)  
    9.         {  
    10.             this.CONNECT_TIME_OUT = timeOut;  
    11.             this.MONGO_CONN_HOST = host;  
    12.         }  
    13.   
    14.         /// <summary>  
    15.         /// 数据库所在主机  
    16.         /// </summary>  
    17.         private readonly string MONGO_CONN_HOST;  
    18.   
    19.         /// <summary>  
    20.         /// 数据库所在主机的端口  
    21.         /// </summary>  
    22.         private readonly int MONGO_CONN_PORT = 27017;  
    23.   
    24.         /// <summary>  
    25.         /// 连接超时设置 秒  
    26.         /// </summary>  
    27.         private readonly string CONNECT_TIME_OUT;  
    28.   
    29.         /// <summary>  
    30.         /// 数据库的名称  
    31.         /// </summary>  
    32.         private readonly string DB_NAME = "Mdemo";  
    33.   
    34.         /// <summary>  
    35.         /// 得到数据库实例  
    36.         /// </summary>  
    37.         /// <returns></returns>  
    38.         public MongoDatabase GetDataBase()  
    39.         {  
    40.             MongoClientSettings mongoSetting = new MongoClientSettings();  
    41.             //设置连接超时时间  
    42.             mongoSetting.ConnectTimeout = new TimeSpan(int.Parse(CONNECT_TIME_OUT) * TimeSpan.TicksPerSecond);  
    43.             //设置数据库服务器  
    44.             mongoSetting.Server = new MongoServerAddress(MONGO_CONN_HOST, MONGO_CONN_PORT);  
    45.             //创建Mongo的客户端  
    46.             MongoClient client = new MongoClient(mongoSetting);  
    47.             //得到服务器端并且生成数据库实例  
    48.             return client.GetServer().GetDatabase(DB_NAME);  
    49.         }  
    50.     }  
    51. }  

    [csharp] view plain copy
     
     print?
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Text;  
    5.   
    6. namespace DAL  
    7. {  
    8.     /// <summary>  
    9.     /// Mongodb数据库的字段特性  主要是设置索引之用  
    10.     /// </summary>  
    11.     [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]  
    12.     public class MongoDbFieldAttribute : Attribute  
    13.     {  
    14.         /// <summary>  
    15.         /// 是否是索引  
    16.         /// </summary>  
    17.         public bool IsIndex { get; set; }  
    18.   
    19.         /// <summary>  
    20.         /// 是否是唯一的  默认flase  
    21.         /// </summary>  
    22.         public bool Unique { get; set; }  
    23.   
    24.         /// <summary>  
    25.         /// 是否是升序 默认true  
    26.         /// </summary>  
    27.         public bool Ascending { get; set; }  
    28.   
    29.         public MongoDbFieldAttribute(bool _isIndex)  
    30.         {  
    31.             this.IsIndex = _isIndex;  
    32.             this.Unique = false;  
    33.             this.Ascending = true;  
    34.         }  
    35.     }  
    36. }  
    [csharp] view plain copy
     
     print?
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using MongoDB.Driver;  
    5. using MongoDB.Bson;  
    6. using MongoDB.Driver.Builders;  
    7. using System.Reflection;  
    8.   
    9.   
    10. namespace DAL  
    11. {  
    12.     /// <summary>  
    13.     /// Mongo db的数据库帮助类  
    14.     /// </summary>  
    15.     public class MongoDbHelper  
    16.     {  
    17.         /// <summary>  
    18.         /// 数据库的实例  
    19.         /// </summary>  
    20.         private MongoDatabase _db;  
    21.   
    22.         /// <summary>  
    23.         /// ObjectId的键  
    24.         /// </summary>  
    25.         private readonly string OBJECTID_KEY = "_id";  
    26.   
    27.         public MongoDbHelper(string host,string timeOut)  
    28.         {  
    29.             this._db = new MongoDb(host,timeOut).GetDataBase();  
    30.         }  
    31.   
    32.         public MongoDbHelper(MongoDatabase db)  
    33.         {  
    34.             this._db = db;  
    35.         }  
    36.   
    37.         public T GetNextSequence<T>(IMongoQuery query, SortByDocument sortBy, UpdateDocument update, string collectionName,string indexName)  
    38.         {  
    39.             if (this._db == null)  
    40.             {  
    41.                 return default(T);  
    42.             }  
    43.             try  
    44.             {  
    45.                 MongoCollection<T> mc = this._db.GetCollection<T>(collectionName);  
    46.                 query = this.InitQuery(query);  
    47.                 sortBy = this.InitSortBy(sortBy, OBJECTID_KEY);  
    48.                 update = this.InitUpdateDocument(update, indexName);  
    49.                 var ido = mc.FindAndModify(query, sortBy, update, true, false);  
    50.   
    51.                 return ido.GetModifiedDocumentAs<T>();  
    52.             }  
    53.             catch (Exception ex)  
    54.             {  
    55.                 return default(T);  
    56.             }  
    57.         }  
    58.  
    59.         #region 插入数据  
    60.         /// <summary>  
    61.         /// 将数据插入进数据库  
    62.         /// </summary>  
    63.         /// <typeparam name="T">需要插入数据的类型</typeparam>  
    64.         /// <param name="t">需要插入的具体实体</param>  
    65.         public bool Insert<T>(T t)  
    66.         {  
    67.             //集合名称  
    68.             string collectionName = typeof(T).Name;  
    69.             return Insert<T>(t, collectionName);  
    70.         }  
    71.   
    72.         /// <summary>  
    73.         /// 将数据插入进数据库  
    74.         /// </summary>  
    75.         /// <typeparam name="T">需要插入数据库的实体类型</typeparam>  
    76.         /// <param name="t">需要插入数据库的具体实体</param>  
    77.         /// <param name="collectionName">指定插入的集合</param>  
    78.         public bool Insert<T>(T t, string collectionName)  
    79.         {  
    80.             if (this._db == null)  
    81.             {  
    82.                 return false;  
    83.             }  
    84.             try  
    85.             {  
    86.                 MongoCollection<BsonDocument> mc = this._db.GetCollection<BsonDocument>(collectionName);  
    87.                 //将实体转换为bson文档  
    88.                 BsonDocument bd = t.ToBsonDocument();  
    89.                 //进行插入操作  
    90.                 WriteConcernResult result = mc.Insert(bd);  
    91.                 if (!string.IsNullOrEmpty(result.ErrorMessage))  
    92.                 {  
    93.                     return false;  
    94.                 }  
    95.                 return true;  
    96.             }  
    97.             catch (Exception ex)  
    98.             {  
    99.                 return false;  
    100.             }  
    101.         }  
    102.   
    103.         /// <summary>  
    104.         /// 批量插入数据  
    105.         /// </summary>  
    106.         /// <typeparam name="T">需要插入数据库的实体类型</typeparam>  
    107.         /// <param name="list">需要插入数据的列表</param>  
    108.         public bool Insert<T>(List<T> list)  
    109.         {  
    110.             //集合名称  
    111.             string collectionName = typeof(T).Name;  
    112.             return this.Insert<T>(list, collectionName);  
    113.         }  
    114.   
    115.         /// <summary>  
    116.         /// 批量插入数据  
    117.         /// </summary>  
    118.         /// <typeparam name="T">需要插入数据库的实体类型</typeparam>  
    119.         /// <param name="list">需要插入数据的列表</param>  
    120.         /// <param name="collectionName">指定要插入的集合</param>  
    121.         public bool Insert<T>(List<T> list, string collectionName)  
    122.         {  
    123.             if (this._db == null)  
    124.             {  
    125.                 return false;  
    126.             }  
    127.             try  
    128.             {  
    129.                 MongoCollection<BsonDocument> mc = this._db.GetCollection<BsonDocument>(collectionName);  
    130.                 //创建一个空间bson集合  
    131.                 List<BsonDocument> bsonList = new List<BsonDocument>();  
    132.                 //批量将数据转为bson格式 并且放进bson文档  
    133.                 list.ForEach(t => bsonList.Add(t.ToBsonDocument()));  
    134.                 //批量插入数据  
    135.                 mc.InsertBatch(bsonList);  
    136.                 return true;  
    137.             }  
    138.             catch (Exception ex)  
    139.             {  
    140.                 return false;  
    141.             }  
    142.         }  
    143.         #endregion  
    144.  
    145.         #region 查询数据  
    146.  
    147.         #region 查询所有记录  
    148.         /// <summary>  
    149.         /// 查询一个集合中的所有数据  
    150.         /// </summary>  
    151.         /// <typeparam name="T">该集合数据的所属类型</typeparam>  
    152.         /// <param name="collectionName">指定集合的名称</param>  
    153.         /// <returns>返回一个List列表</returns>  
    154.         public List<T> FindAll<T>(string collectionName)  
    155.         {  
    156.             if (this._db == null)  
    157.             {  
    158.                 return null;  
    159.             }  
    160.             try  
    161.             {  
    162.                 MongoCollection<T> mc = this._db.GetCollection<T>(collectionName);  
    163.                 //以实体方式取出其数据集合  
    164.                 MongoCursor<T> mongoCursor = mc.FindAll();  
    165.                 //直接转化为List返回  
    166.                 return mongoCursor.ToList<T>();  
    167.             }  
    168.             catch (Exception ex)  
    169.             {  
    170.                 return null;  
    171.             }  
    172.         }  
    173.   
    174.         /// <summary>  
    175.         /// 查询一个集合中的所有数据 其集合的名称为T的名称  
    176.         /// </summary>  
    177.         /// <typeparam name="T">该集合数据的所属类型</typeparam>  
    178.         /// <returns>返回一个List列表</returns>  
    179.         public List<T> FindAll<T>()  
    180.         {  
    181.             string collectionName = typeof(T).Name;  
    182.             return FindAll<T>(collectionName);  
    183.         }  
    184.         #endregion  
    185.  
    186.         #region 查询一条记录  
    187.         /// <summary>  
    188.         /// 查询索引最大的一条记录  
    189.         /// </summary>  
    190.         /// <typeparam name="T">该数据所属的类型</typeparam>  
    191.         /// <param name="collectionName">去指定查询的集合</param>  
    192.         /// <param name="sort">排序字段</param>  
    193.         /// <returns>返回一个实体类型</returns>  
    194.         public T FindOneToIndexMax<T>(string collectionName, string[] sort)  
    195.         {  
    196.             return FindOneToIndexMax<T>(null, collectionName, sort);  
    197.         }  
    198.   
    199.         /// <summary>  
    200.         /// 查询索引最大的一条记录  
    201.         /// </summary>  
    202.         /// <typeparam name="T">该数据所属的类型</typeparam>  
    203.         /// <param name="query">查询的条件 可以为空</param>  
    204.         /// <param name="collectionName">去指定查询的集合</param>  
    205.         /// <param name="sort">排序字段</param>  
    206.         /// <returns>返回一个实体类型</returns>  
    207.         public T FindOneToIndexMax<T>(IMongoQuery query,string collectionName, string[] sort)  
    208.         {  
    209.             if (this._db == null)  
    210.             {  
    211.                 return default(T);  
    212.             }  
    213.             try  
    214.             {  
    215.                 MongoCollection<T> mc = this._db.GetCollection<T>(collectionName);  
    216.                 query = this.InitQuery(query);  
    217.                 T t = mc.Find(query).SetSortOrder(SortBy.Descending(sort)).FirstOrDefault<T>();  
    218.                 return t;  
    219.             }  
    220.             catch (Exception ex)  
    221.             {  
    222.                 return default(T);  
    223.             }  
    224.         }  
    225.         /// <summary>  
    226.         /// 查询一条记录  
    227.         /// </summary>  
    228.         /// <typeparam name="T">该数据所属的类型</typeparam>  
    229.         /// <param name="query">查询的条件 可以为空</param>  
    230.         /// <param name="collectionName">去指定查询的集合</param>  
    231.         /// <returns>返回一个实体类型</returns>  
    232.         public T FindOne<T>(IMongoQuery query, string collectionName)  
    233.         {  
    234.             if (this._db == null)  
    235.             {  
    236.                 return default(T);  
    237.             }  
    238.             try  
    239.             {  
    240.                 MongoCollection<T> mc = this._db.GetCollection<T>(collectionName);  
    241.                 query = this.InitQuery(query);  
    242.                 T t = mc.FindOne(query);  
    243.                 return t;  
    244.             }  
    245.             catch (Exception ex)  
    246.             {  
    247.                 return default(T);  
    248.             }  
    249.         }  
    250.   
    251.         /// <summary>  
    252.         /// 查询一条记录  
    253.         /// </summary>  
    254.         /// <typeparam name="T">该数据所属的类型</typeparam>  
    255.         /// <param name="collectionName">去指定查询的集合</param>  
    256.         /// <returns>返回一个实体类型</returns>  
    257.         public T FindOne<T>(string collectionName)  
    258.         {  
    259.             return FindOne<T>(null, collectionName);  
    260.         }  
    261.   
    262.         /// <summary>  
    263.         /// 查询一条记录  
    264.         /// </summary>  
    265.         /// <typeparam name="T">该数据所属的类型</typeparam>  
    266.         /// <returns>返回一个实体类型</returns>  
    267.         public T FindOne<T>()  
    268.         {  
    269.             string collectionName = typeof(T).Name;  
    270.             return FindOne<T>(null, collectionName);  
    271.         }  
    272.   
    273.   
    274.         /// <summary>  
    275.         /// 查询一条记录  
    276.         /// </summary>  
    277.         /// <typeparam name="T">该数据所属的类型</typeparam>  
    278.         /// <param name="query">查询的条件 可以为空</param>  
    279.         /// <returns>返回一个实体类型</returns>  
    280.         public T FindOne<T>(IMongoQuery query)  
    281.         {  
    282.             string collectionName = typeof(T).Name;  
    283.             return FindOne<T>(query, collectionName);  
    284.         }  
    285.         #endregion  
    286.  
    287.         #region 普通的条件查询  
    288.         /// <summary>  
    289.         /// 根据指定条件查询集合中的数据  
    290.         /// </summary>  
    291.         /// <typeparam name="T">该集合数据的所属类型</typeparam>  
    292.         /// <param name="query">指定的查询条件 比如Query.And(Query.EQ("username","admin"),Query.EQ("password":"admin"))</param>  
    293.         /// <param name="collectionName">指定的集合的名称</param>  
    294.         /// <returns>返回一个List列表</returns>  
    295.         public List<T> Find<T>(IMongoQuery query, string collectionName)  
    296.         {  
    297.             if (this._db == null)  
    298.             {  
    299.                 return null;  
    300.             }  
    301.             try  
    302.             {  
    303.                 MongoCollection<T> mc = this._db.GetCollection<T>(collectionName);  
    304.                 query = this.InitQuery(query);  
    305.                 MongoCursor<T> mongoCursor = mc.Find(query);  
    306.                 return mongoCursor.ToList<T>();  
    307.             }  
    308.             catch (Exception ex)  
    309.             {  
    310.                 return null;  
    311.             }  
    312.         }  
    313.   
    314.         /// <summary>  
    315.         /// 根据指定条件查询集合中的数据  
    316.         /// </summary>  
    317.         /// <typeparam name="T">该集合数据的所属类型</typeparam>  
    318.         /// <param name="query">指定的查询条件 比如Query.And(Query.EQ("username","admin"),Query.EQ("password":"admin"))</param>  
    319.         /// <returns>返回一个List列表</returns>  
    320.         public List<T> Find<T>(IMongoQuery query)  
    321.         {  
    322.             string collectionName = typeof(T).Name;  
    323.             return this.Find<T>(query,collectionName);  
    324.         }  
    325.         #endregion  
    326.  
    327.         #region 分页查询 PageIndex和PageSize模式  在页数PageIndex大的情况下 效率明显变低  
    328.   
    329.         /// <summary>  
    330.         /// 分页查询 PageIndex和PageSize模式  在页数PageIndex大的情况下 效率明显变低  
    331.         /// </summary>  
    332.         /// <typeparam name="T">所需查询的数据的实体类型</typeparam>  
    333.         /// <param name="query">查询的条件</param>  
    334.         /// <param name="pageIndex">当前的页数</param>  
    335.         /// <param name="pageSize">当前的尺寸</param>  
    336.         /// <param name="sortBy">排序方式</param>  
    337.         /// <param name="collectionName">集合名称</param>  
    338.         /// <returns>返回List列表</returns>  
    339.         public List<T> Find<T>(IMongoQuery query, int pageIndex, int pageSize, SortByDocument sortBy, string collectionName)  
    340.         {  
    341.             if (this._db == null)  
    342.             {  
    343.                 return null;  
    344.             }  
    345.             try  
    346.             {  
    347.                 MongoCollection<T> mc = this._db.GetCollection<T>(collectionName);  
    348.                 MongoCursor<T> mongoCursor = null;  
    349.                 query = this.InitQuery(query);  
    350.                 sortBy = this.InitSortBy(sortBy, OBJECTID_KEY);  
    351.                 //如页序号为0时初始化为1  
    352.                 pageIndex = pageIndex == 0 ? 1 : pageIndex;  
    353.                 //按条件查询 排序 跳数 取数  
    354.                 mongoCursor = mc.Find(query).SetSortOrder(sortBy).SetSkip((pageIndex - 1) * pageSize).SetLimit(pageSize);  
    355.                 return mongoCursor.ToList<T>();  
    356.             }  
    357.             catch (Exception ex)  
    358.             {  
    359.                 return null;  
    360.             }  
    361.         }  
    362.   
    363.         /// <summary>  
    364.         /// 分页查询 PageIndex和PageSize模式  在页数PageIndex大的情况下 效率明显变低  
    365.         /// </summary>  
    366.         /// <typeparam name="T">所需查询的数据的实体类型</typeparam>  
    367.         /// <param name="query">查询的条件</param>  
    368.         /// <param name="pageIndex">当前的页数</param>  
    369.         /// <param name="pageSize">当前的尺寸</param>  
    370.         /// <param name="sortBy">排序方式</param>  
    371.         /// <returns>返回List列表</returns>  
    372.         public List<T> Find<T>(IMongoQuery query, int pageIndex, int pageSize, SortByDocument sortBy)  
    373.         {  
    374.             string collectionName = typeof(T).Name;  
    375.             return this.Find<T>(query, pageIndex, pageSize, sortBy, collectionName);  
    376.         }  
    377.  
    378.         #endregion  
    379.  
    380.         #region 分页查询 指定索引最后项-PageSize模式  
    381.   
    382.         /// <summary>  
    383.         /// 分页查询 指定索引最后项-PageSize模式   
    384.         /// </summary>  
    385.         /// <typeparam name="T">所需查询的数据的实体类型</typeparam>  
    386.         /// <param name="query">查询的条件 没有可以为null</param>  
    387.         /// <param name="indexName">索引名称</param>  
    388.         /// <param name="lastKeyValue">最后索引的值</param>  
    389.         /// <param name="pageSize">分页的尺寸</param>  
    390.         /// <param name="sortType">排序类型 1升序 -1降序 仅仅针对该索引</param>  
    391.         /// <param name="collectionName">指定的集合名称</param>  
    392.         /// <returns>返回一个List列表数据</returns>  
    393.         public List<T> Find<T>(IMongoQuery query, string indexName, object lastKeyValue, int pageSize, int sortType, string collectionName)  
    394.         {  
    395.             if (this._db == null)  
    396.             {  
    397.                 return null;  
    398.             }  
    399.             try  
    400.             {  
    401.                 MongoCollection<T> mc = this._db.GetCollection<T>(collectionName);  
    402.                 MongoCursor<T> mongoCursor = null;  
    403.                 query = this.InitQuery(query);  
    404.   
    405.                 //判断升降序后进行查询  
    406.                 if (sortType > 0)  
    407.                 {  
    408.                     //升序  
    409.                     if (lastKeyValue != null)  
    410.                     {  
    411.                         //有上一个主键的值传进来时才添加上一个主键的值的条件  
    412.                         query = Query.And(query, Query.GT(indexName, BsonValue.Create(lastKeyValue)));  
    413.                     }  
    414.                     //先按条件查询 再排序 再取数  
    415.                     mongoCursor = mc.Find(query).SetSortOrder(new SortByDocument(indexName, 1)).SetLimit(pageSize);  
    416.                 }  
    417.                 else  
    418.                 {  
    419.                     //降序  
    420.                     if (lastKeyValue != null)  
    421.                     {  
    422.                         query = Query.And(query, Query.LT(indexName, BsonValue.Create(lastKeyValue)));  
    423.                     }  
    424.                     mongoCursor = mc.Find(query).SetSortOrder(new SortByDocument(indexName, -1)).SetLimit(pageSize);  
    425.                 }  
    426.                 return mongoCursor.ToList<T>();  
    427.             }  
    428.             catch (Exception ex)  
    429.             {  
    430.                 return null;  
    431.             }  
    432.         }  
    433.   
    434.         /// <summary>  
    435.         /// 分页查询 指定索引最后项-PageSize模式   
    436.         /// </summary>  
    437.         /// <typeparam name="T">所需查询的数据的实体类型</typeparam>  
    438.         /// <param name="query">查询的条件 没有可以为null</param>  
    439.         /// <param name="indexName">索引名称</param>  
    440.         /// <param name="lastKeyValue">最后索引的值</param>  
    441.         /// <param name="pageSize">分页的尺寸</param>  
    442.         /// <param name="sortType">排序类型 1升序 -1降序 仅仅针对该索引</param>  
    443.         /// <returns>返回一个List列表数据</returns>  
    444.         public List<T> Find<T>(IMongoQuery query, string indexName, object lastKeyValue, int pageSize, int sortType)  
    445.         {  
    446.             string collectionName = typeof(T).Name;  
    447.             return this.Find<T>(query, indexName, lastKeyValue, pageSize, sortType, collectionName);  
    448.         }  
    449.   
    450.         /// <summary>  
    451.         /// 分页查询 指定ObjectId最后项-PageSize模式   
    452.         /// </summary>  
    453.         /// <typeparam name="T">所需查询的数据的实体类型</typeparam>  
    454.         /// <param name="query">查询的条件 没有可以为null</param>  
    455.         /// <param name="lastObjectId">上一条记录的ObjectId 没有可以为空</param>  
    456.         /// <param name="pageSize">每页尺寸</param>  
    457.         /// <param name="sortType">排序类型 1升序 -1降序 仅仅针对_id</param>  
    458.         /// <param name="collectionName">指定去查询集合的名称</param>  
    459.         /// <returns>返回一个List列表数据</returns>  
    460.         public List<T> Find<T>(IMongoQuery query, string lastObjectId, int pageSize, int sortType, string collectionName)  
    461.         {  
    462.             return this.Find<T>(query, OBJECTID_KEY, new ObjectId(lastObjectId), pageSize, sortType, collectionName);  
    463.         }  
    464.   
    465.         /// <summary>  
    466.         /// 分页查询 指定ObjectId最后项-PageSize模式   
    467.         /// </summary>  
    468.         /// <typeparam name="T">所需查询的数据的实体类型</typeparam>  
    469.         /// <param name="query">查询的条件 没有可以为null</param>  
    470.         /// <param name="lastObjectId">上一条记录的ObjectId 没有可以为空</param>  
    471.         /// <param name="pageSize">每页尺寸</param>  
    472.         /// <param name="sortType">排序类型 1升序 -1降序 仅仅针对_id</param>  
    473.         /// <returns>返回一个List列表数据</returns>  
    474.         public List<T> Find<T>(IMongoQuery query, string lastObjectId, int pageSize, int sortType)  
    475.         {  
    476.             string collectionName = typeof(T).Name;  
    477.             return Find<T>(query, lastObjectId, pageSize, sortType, collectionName);  
    478.         }  
    479.  
    480.         #endregion  
    481.  
    482.  
    483.         #endregion  
    484.  
    485.         #region 更新数据  
    486.   
    487.         /// <summary>  
    488.         /// 更新数据  
    489.         /// </summary>  
    490.         /// <typeparam name="T">更新的数据 所属的类型</typeparam>  
    491.         /// <param name="query">更新数据的查询</param>  
    492.         /// <param name="update">需要更新的文档</param>  
    493.         /// <param name="collectionName">指定更新集合的名称</param>  
    494.         public bool Update<T>(IMongoQuery query, IMongoUpdate update, string collectionName)  
    495.         {  
    496.             if (this._db == null)  
    497.             {  
    498.                 return false;  
    499.             }  
    500.             try  
    501.             {  
    502.                 MongoCollection<T> mc = this._db.GetCollection<T>(collectionName);  
    503.                 query = this.InitQuery(query);  
    504.                 //更新数据  
    505.                 WriteConcernResult result = mc.Update(query, update, UpdateFlags.Multi);  
    506.                 return true;  
    507.             }  
    508.             catch (Exception ex)  
    509.             {  
    510.                 return false;                 
    511.             }  
    512.         }  
    513.   
    514.         /// <summary>  
    515.         /// 更新数据  
    516.         /// </summary>  
    517.         /// <typeparam name="T">更新的数据 所属的类型</typeparam>  
    518.         /// <param name="query">更新数据的查询</param>  
    519.         /// <param name="update">需要更新的文档</param>  
    520.         public bool Update<T>(IMongoQuery query, IMongoUpdate update)  
    521.         {  
    522.             string collectionName = typeof(T).Name;  
    523.             return this.Update<T>(query, update, collectionName);  
    524.         }  
    525.  
    526.         #endregion  
    527.  
    528.         #region 移除/删除数据  
    529.         /// <summary>  
    530.         /// 移除指定的数据  
    531.         /// </summary>  
    532.         /// <typeparam name="T">移除的数据类型</typeparam>  
    533.         /// <param name="query">移除的数据条件</param>  
    534.         /// <param name="collectionName">指定的集合名词</param>  
    535.         public bool Remove<T>(IMongoQuery query, string collectionName)  
    536.         {  
    537.             if (this._db == null)  
    538.             {  
    539.                 return false;  
    540.             }  
    541.             try  
    542.             {  
    543.                 MongoCollection<T> mc = this._db.GetCollection<T>(collectionName);  
    544.                 query = this.InitQuery(query);  
    545.                 //根据指定查询移除数据  
    546.                 mc.Remove(query);  
    547.                 return true;  
    548.             }  
    549.             catch (Exception ex)  
    550.             {  
    551.                 return false;  
    552.             }  
    553.         }  
    554.   
    555.         /// <summary>  
    556.         /// 移除指定的数据  
    557.         /// </summary>  
    558.         /// <typeparam name="T">移除的数据类型</typeparam>  
    559.         /// <param name="query">移除的数据条件</param>  
    560.         public bool Remove<T>(IMongoQuery query)  
    561.         {  
    562.             string collectionName = typeof(T).Name;  
    563.             return this.Remove<T>(query,collectionName);  
    564.         }  
    565.   
    566.         /// <summary>  
    567.         /// 移除实体里面所有的数据  
    568.         /// </summary>  
    569.         /// <typeparam name="T">移除的数据类型</typeparam>  
    570.         public bool ReomveAll<T>()  
    571.         {  
    572.             string collectionName = typeof(T).Name;  
    573.             return this.Remove<T>(null,collectionName);  
    574.         }  
    575.   
    576.         /// <summary>  
    577.         /// 移除实体里面所有的数据  
    578.         /// </summary>  
    579.         /// <typeparam name="T">移除的数据类型</typeparam>  
    580.         /// <param name="collectionName">指定的集合名称</param>  
    581.         public bool RemoveAll<T>(string collectionName)  
    582.         {  
    583.             return this.Remove<T>(null,collectionName);  
    584.         }  
    585.         #endregion  
    586.  
    587.         #region 创建索引  
    588.         /// <summary>  
    589.         /// 创建索引   
    590.         /// </summary>  
    591.         /// <typeparam name="T">需要创建索引的实体类型</typeparam>  
    592.         public bool CreateIndex<T>()  
    593.         {  
    594.             if (this._db == null)  
    595.             {  
    596.                 return false;  
    597.             }  
    598.             try  
    599.             {  
    600.                 string collectionName = typeof(T).Name;  
    601.                 MongoCollection<BsonDocument> mc = this._db.GetCollection<BsonDocument>(collectionName);  
    602.   
    603.                 PropertyInfo[] propertys = typeof(T).GetProperties(BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty);  
    604.                 //得到该实体类型的属性  
    605.                 foreach (PropertyInfo property in propertys)  
    606.                 {  
    607.                     //在各个属性中得到其特性  
    608.                     foreach (object obj in property.GetCustomAttributes(true))  
    609.                     {  
    610.                         MongoDbFieldAttribute mongoField = obj as MongoDbFieldAttribute;  
    611.                         if (mongoField != null)  
    612.                         {// 此特性为mongodb的字段属性  
    613.   
    614.                             IndexKeysBuilder indexKey;  
    615.                             if (mongoField.Ascending)  
    616.                             {  
    617.                                 //升序 索引  
    618.                                 indexKey = IndexKeys.Ascending(property.Name);  
    619.                             }  
    620.                             else  
    621.                             {  
    622.                                 //降序索引  
    623.                                 indexKey = IndexKeys.Descending(property.Name);  
    624.                             }  
    625.                             //创建该属性  
    626.                             mc.CreateIndex(indexKey, IndexOptions.SetUnique(mongoField.Unique));  
    627.                         }  
    628.                     }  
    629.                 }  
    630.                 return true;  
    631.             }  
    632.             catch (Exception ex)  
    633.             {  
    634.                 return false;  
    635.             }  
    636.         }  
    637.         #endregion  
    638.  
    639.         #region 获取表的行数  
    640.         /// <summary>  
    641.         /// 获取数据表总行数  
    642.         /// </summary>  
    643.         /// <typeparam name="T"></typeparam>  
    644.         /// <param name="query"></param>  
    645.         /// <param name="collectionName"></param>  
    646.         /// <returns></returns>  
    647.         public long GetCount<T>(IMongoQuery query,string collectionName)  
    648.         {  
    649.             if (this._db == null)  
    650.             {  
    651.                 return 0;  
    652.             }  
    653.             try  
    654.             {  
    655.                 MongoCollection<T> mc = this._db.GetCollection<T>(collectionName);  
    656.                 if (query == null)  
    657.                 {  
    658.                     return mc.Count();  
    659.                 }  
    660.                 else  
    661.                 {  
    662.                     return mc.Count(query);  
    663.                 }                 
    664.             }  
    665.             catch (Exception ex)  
    666.             {  
    667.                 return 0;  
    668.             }  
    669.         }  
    670.         /// <summary>  
    671.         /// 获取数据表总行数  
    672.         /// </summary>  
    673.         /// <typeparam name="T"></typeparam>  
    674.         /// <param name="query"></param>  
    675.         /// <returns></returns>  
    676.         public long GetCount<T>(IMongoQuery query)  
    677.         {  
    678.             string collectionName = typeof(T).Name;  
    679.             return GetCount<T>(query,collectionName);  
    680.         }  
    681.  
    682.         #endregion  
    683.  
    684.         #region 获取集合的存储大小  
    685.         /// <summary>  
    686.         /// 获取集合的存储大小  
    687.         /// </summary>  
    688.         /// <typeparam name="T">该集合对应的实体类</typeparam>  
    689.         /// <returns>返回一个long型</returns>  
    690.         public long GetDataSize<T>()  
    691.         {  
    692.             string collectionName = typeof(T).Name;  
    693.             return GetDataSize(collectionName);  
    694.         }  
    695.   
    696.         /// <summary>  
    697.         /// 获取集合的存储大小  
    698.         /// </summary>  
    699.         /// <param name="collectionName">该集合对应的名称</param>  
    700.         /// <returns>返回一个long型</returns>  
    701.         public long GetDataSize(string collectionName)  
    702.         {  
    703.             if (this._db == null)  
    704.             {  
    705.                 return 0;  
    706.             }  
    707.             try  
    708.             {  
    709.                 MongoCollection<BsonDocument> mc = this._db.GetCollection<BsonDocument>(collectionName);  
    710.                 return mc.GetTotalStorageSize();  
    711.             }  
    712.             catch (Exception ex)  
    713.             {  
    714.                 return 0;  
    715.             }  
    716.         }  
    717.  
    718.  
    719.         #endregion  
    720.  
    721.         #region 私有的一些辅助方法  
    722.         /// <summary>  
    723.         /// 初始化查询记录 主要当该查询条件为空时 会附加一个恒真的查询条件,防止空查询报错  
    724.         /// </summary>  
    725.         /// <param name="query">查询的条件</param>  
    726.         /// <returns></returns>  
    727.         private IMongoQuery InitQuery(IMongoQuery query)  
    728.         {  
    729.             if (query == null)  
    730.             {  
    731.                 //当查询为空时 附加恒真的条件 类似SQL:1=1的语法  
    732.                 query = Query.Exists(OBJECTID_KEY);  
    733.             }  
    734.             return query;  
    735.         }  
    736.   
    737.         /// <summary>  
    738.         /// 初始化排序条件  主要当条件为空时 会默认以ObjectId递增的一个排序  
    739.         /// </summary>  
    740.         /// <param name="sortBy"></param>  
    741.         /// <param name="sortByName"></param>  
    742.         /// <returns></returns>  
    743.         private SortByDocument InitSortBy(SortByDocument sortBy, string sortByName)  
    744.         {  
    745.             if (sortBy == null)  
    746.             {  
    747.                 //默认ObjectId 递增  
    748.                 sortBy = new SortByDocument(sortByName, -1);  
    749.             }  
    750.             return sortBy;  
    751.         }  
    752.   
    753.         private UpdateDocument InitUpdateDocument(UpdateDocument update,string indexName)  
    754.         {  
    755.             if (update == null)  
    756.             {  
    757.                 update = new UpdateDocument("$inc", new QueryDocument(indexName, 0));  
    758.             }  
    759.             return update;  
    760.         }  
    761.         #endregion  
    762.     }  
    763. }  

    4.调用:先引用库文件:

    [csharp] view plain copy
     
     print?
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Web;  
    5. using System.Web.Mvc;  
    6. using MongoDB;  
    7. using MongoDbDemo;  
    8. using MongoDB.Driver;  
    9. using MongoDB.Bson;  
    10. using DAL.Entity;  
    11. using DAL;  
    12. using MongoDB.Driver.Builders;  
    13. using System.Diagnostics;  
    14.   
    15. namespace MongoDbDemo.Controllers  
    16. {  
    17.     public class HomeController : Controller  
    18.     {  
    19.         //  
    20.         // GET: /Home/  
    21.   
    22.         public ActionResult Index()  
    23.         {  
    24.             return Content("MongoDbDemo");  
    25.         }  
    26.  
    27.         #region INSERT  
    28.         /// <summary>  
    29.         /// 添加用户  
    30.         /// </summary>  
    31.         /// <returns></returns>  
    32.         public ActionResult Ruser()  
    33.         {  
    34.             try  
    35.             {  
    36.                 string name = Request["name"];  
    37.                 string age = Request["age"];  
    38.                 User user1 = new User { Uname = name, Age = age };  
    39.                 MongoDbHelper mh = new MongoDbHelper("127.0.0.1", "1000");  
    40.                 if (mh.Insert<User>(user1))  
    41.                 {  
    42.                     return Json(new { success = "true" });  
    43.                 }  
    44.             }  
    45.             catch (Exception)  
    46.             {  
    47.                 return Json(new { success = "filled" });  
    48.                 throw;  
    49.             }  
    50.             return Json(new { success = "filled" });  
    51.         }  
    52.         #endregion  
    53.  
    54.         #region SELECT  
    55.         /// <summary>  
    56.         /// 查询一个集合中的所有数据  
    57.         /// </summary>  
    58.         /// <returns></returns>  
    59.         public ActionResult Seluser()  
    60.         {             
    61.             MongoDbHelper mh = new MongoDbHelper("127.0.0.1", "1000");  
    62.             List<User> users = mh.FindAll<User>();  
    63.             return Json(new { success="true"});  
    64.         }  
    65.   
    66.         /// <summary>  
    67.         /// 按条件查询一条数据  
    68.         /// </summary>  
    69.         /// <returns></returns>  
    70.         public ActionResult SelOne()  
    71.         {  
    72.             string name = Request["name"];  
    73.             string age=Request["age"];  
    74.             MongoDbHelper mh = new MongoDbHelper("127.0.0.1", "1000");  
    75.             User users = mh.FindOne<User>(Query.And(Query.EQ("Uname", name), Query.EQ("Age", age)));  
    76.             return Json(new {success="true" ,users=users});  
    77.         }  
    78.   
    79.         /// <summary>  
    80.         /// 分页查询  
    81.         /// </summary>  
    82.         /// <returns></returns>  
    83.         public ActionResult SelPage()   
    84.         {  
    85.             int pageindex=int.Parse(Request["pageindex"]);//页索引  
    86.             int pagesize = int.Parse(Request["pagesize"]);//行数  
    87.             MongoDbHelper mh = new MongoDbHelper("127.0.0.1", "1000");  
    88.             Stopwatch sw1 = new Stopwatch();  
    89.             sw1.Start();  
    90.             List<User> users = mh.Find<User>(null,pageindex,pagesize,null);  
    91.             return Json(new {success="true",users=users });  
    92.         }  
    93.         #endregion  
    94.  
    95.         #region UPDATE  
    96.         /// <summary>  
    97.         /// 修改信息  
    98.         /// </summary>  
    99.         /// <returns></returns>  
    100.         public ActionResult upduser()  
    101.         {  
    102.             MongoDbHelper mh = new MongoDbHelper("127.0.0.1", "1000");  
    103.             if (mh.Update<User>(Query.EQ("Uname", "阿斯达"), Update.Set("Uname", "阿斯达s"), "User"))  
    104.             {  
    105.                 return Json(new { success = "true" });  
    106.             }  
    107.             else  
    108.             {  
    109.                 return Json(new { success = "fales" });  
    110.             }  
    111.   
    112.         }  
    113.         #endregion  
    114.  
    115.         #region DELETE  
    116.         /// <summary>  
    117.         /// 删除消息  
    118.         /// </summary>  
    119.         /// <returns></returns>  
    120.         public ActionResult deluser()   
    121.         {  
    122.             MongoDbHelper mh = new MongoDbHelper("127.0.0.1", "1000");  
    123.             if (mh.Remove<User>(Query.EQ("Uname", "阿斯达s")))  
    124.             {  
    125.                 return Json(new { success = "true" });  
    126.             }  
    127.             else {  
    128.                 return Json(new { success = "fales" });  
    129.             }  
    130.         }  
    131.         #endregion  
    132.     }  
    133. }  
    简单的使用.NET 进行MongoDB的增删改查。
  • 相关阅读:
    web安全之sql注入实例(5.0之前的)
    http和htpps
    web安全之sql注入原理
    web安全之http协议
    题解洛谷P1538【迎春舞会之数字舞蹈】
    [模板]洛谷T3375 KMP字符串匹配
    [模板]洛谷T2158 仪仗队 欧拉函数
    洛谷T1967 货车运输 Kruskal最大生成树&&倍增LCA
    [模板]洛谷T3380 二逼平衡树 线段树套BST
    [模板]洛谷T3384 树链剖分
  • 原文地址:https://www.cnblogs.com/zxtceq/p/7698511.html
Copyright © 2011-2022 走看看