【MongoDB学习-在.NET中的简单操作】
1.新建MVC项目, 管理NuGet包,进入下载MongDB.net库文件
2.新增项目DAL数据访问层,引用以下库文件:
3.C# 访问MongoDB通用方法类:
- using MongoDB.Driver;
- using System;
- namespace DAL
- {
- public class MongoDb
- {
- public MongoDb(string host,string timeOut)
- {
- this.CONNECT_TIME_OUT = timeOut;
- this.MONGO_CONN_HOST = host;
- }
- /// <summary>
- /// 数据库所在主机
- /// </summary>
- private readonly string MONGO_CONN_HOST;
- /// <summary>
- /// 数据库所在主机的端口
- /// </summary>
- private readonly int MONGO_CONN_PORT = 27017;
- /// <summary>
- /// 连接超时设置 秒
- /// </summary>
- private readonly string CONNECT_TIME_OUT;
- /// <summary>
- /// 数据库的名称
- /// </summary>
- private readonly string DB_NAME = "Mdemo";
- /// <summary>
- /// 得到数据库实例
- /// </summary>
- /// <returns></returns>
- public MongoDatabase GetDataBase()
- {
- MongoClientSettings mongoSetting = new MongoClientSettings();
- //设置连接超时时间
- mongoSetting.ConnectTimeout = new TimeSpan(int.Parse(CONNECT_TIME_OUT) * TimeSpan.TicksPerSecond);
- //设置数据库服务器
- mongoSetting.Server = new MongoServerAddress(MONGO_CONN_HOST, MONGO_CONN_PORT);
- //创建Mongo的客户端
- MongoClient client = new MongoClient(mongoSetting);
- //得到服务器端并且生成数据库实例
- return client.GetServer().GetDatabase(DB_NAME);
- }
- }
- }
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace DAL
- {
- /// <summary>
- /// Mongodb数据库的字段特性 主要是设置索引之用
- /// </summary>
- [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
- public class MongoDbFieldAttribute : Attribute
- {
- /// <summary>
- /// 是否是索引
- /// </summary>
- public bool IsIndex { get; set; }
- /// <summary>
- /// 是否是唯一的 默认flase
- /// </summary>
- public bool Unique { get; set; }
- /// <summary>
- /// 是否是升序 默认true
- /// </summary>
- public bool Ascending { get; set; }
- public MongoDbFieldAttribute(bool _isIndex)
- {
- this.IsIndex = _isIndex;
- this.Unique = false;
- this.Ascending = true;
- }
- }
- }
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using MongoDB.Driver;
- using MongoDB.Bson;
- using MongoDB.Driver.Builders;
- using System.Reflection;
- namespace DAL
- {
- /// <summary>
- /// Mongo db的数据库帮助类
- /// </summary>
- public class MongoDbHelper
- {
- /// <summary>
- /// 数据库的实例
- /// </summary>
- private MongoDatabase _db;
- /// <summary>
- /// ObjectId的键
- /// </summary>
- private readonly string OBJECTID_KEY = "_id";
- public MongoDbHelper(string host,string timeOut)
- {
- this._db = new MongoDb(host,timeOut).GetDataBase();
- }
- public MongoDbHelper(MongoDatabase db)
- {
- this._db = db;
- }
- public T GetNextSequence<T>(IMongoQuery query, SortByDocument sortBy, UpdateDocument update, string collectionName,string indexName)
- {
- if (this._db == null)
- {
- return default(T);
- }
- try
- {
- MongoCollection<T> mc = this._db.GetCollection<T>(collectionName);
- query = this.InitQuery(query);
- sortBy = this.InitSortBy(sortBy, OBJECTID_KEY);
- update = this.InitUpdateDocument(update, indexName);
- var ido = mc.FindAndModify(query, sortBy, update, true, false);
- return ido.GetModifiedDocumentAs<T>();
- }
- catch (Exception ex)
- {
- return default(T);
- }
- }
- #region 插入数据
- /// <summary>
- /// 将数据插入进数据库
- /// </summary>
- /// <typeparam name="T">需要插入数据的类型</typeparam>
- /// <param name="t">需要插入的具体实体</param>
- public bool Insert<T>(T t)
- {
- //集合名称
- string collectionName = typeof(T).Name;
- return Insert<T>(t, collectionName);
- }
- /// <summary>
- /// 将数据插入进数据库
- /// </summary>
- /// <typeparam name="T">需要插入数据库的实体类型</typeparam>
- /// <param name="t">需要插入数据库的具体实体</param>
- /// <param name="collectionName">指定插入的集合</param>
- public bool Insert<T>(T t, string collectionName)
- {
- if (this._db == null)
- {
- return false;
- }
- try
- {
- MongoCollection<BsonDocument> mc = this._db.GetCollection<BsonDocument>(collectionName);
- //将实体转换为bson文档
- BsonDocument bd = t.ToBsonDocument();
- //进行插入操作
- WriteConcernResult result = mc.Insert(bd);
- if (!string.IsNullOrEmpty(result.ErrorMessage))
- {
- return false;
- }
- return true;
- }
- catch (Exception ex)
- {
- return false;
- }
- }
- /// <summary>
- /// 批量插入数据
- /// </summary>
- /// <typeparam name="T">需要插入数据库的实体类型</typeparam>
- /// <param name="list">需要插入数据的列表</param>
- public bool Insert<T>(List<T> list)
- {
- //集合名称
- string collectionName = typeof(T).Name;
- return this.Insert<T>(list, collectionName);
- }
- /// <summary>
- /// 批量插入数据
- /// </summary>
- /// <typeparam name="T">需要插入数据库的实体类型</typeparam>
- /// <param name="list">需要插入数据的列表</param>
- /// <param name="collectionName">指定要插入的集合</param>
- public bool Insert<T>(List<T> list, string collectionName)
- {
- if (this._db == null)
- {
- return false;
- }
- try
- {
- MongoCollection<BsonDocument> mc = this._db.GetCollection<BsonDocument>(collectionName);
- //创建一个空间bson集合
- List<BsonDocument> bsonList = new List<BsonDocument>();
- //批量将数据转为bson格式 并且放进bson文档
- list.ForEach(t => bsonList.Add(t.ToBsonDocument()));
- //批量插入数据
- mc.InsertBatch(bsonList);
- return true;
- }
- catch (Exception ex)
- {
- return false;
- }
- }
- #endregion
- #region 查询数据
- #region 查询所有记录
- /// <summary>
- /// 查询一个集合中的所有数据
- /// </summary>
- /// <typeparam name="T">该集合数据的所属类型</typeparam>
- /// <param name="collectionName">指定集合的名称</param>
- /// <returns>返回一个List列表</returns>
- public List<T> FindAll<T>(string collectionName)
- {
- if (this._db == null)
- {
- return null;
- }
- try
- {
- MongoCollection<T> mc = this._db.GetCollection<T>(collectionName);
- //以实体方式取出其数据集合
- MongoCursor<T> mongoCursor = mc.FindAll();
- //直接转化为List返回
- return mongoCursor.ToList<T>();
- }
- catch (Exception ex)
- {
- return null;
- }
- }
- /// <summary>
- /// 查询一个集合中的所有数据 其集合的名称为T的名称
- /// </summary>
- /// <typeparam name="T">该集合数据的所属类型</typeparam>
- /// <returns>返回一个List列表</returns>
- public List<T> FindAll<T>()
- {
- string collectionName = typeof(T).Name;
- return FindAll<T>(collectionName);
- }
- #endregion
- #region 查询一条记录
- /// <summary>
- /// 查询索引最大的一条记录
- /// </summary>
- /// <typeparam name="T">该数据所属的类型</typeparam>
- /// <param name="collectionName">去指定查询的集合</param>
- /// <param name="sort">排序字段</param>
- /// <returns>返回一个实体类型</returns>
- public T FindOneToIndexMax<T>(string collectionName, string[] sort)
- {
- return FindOneToIndexMax<T>(null, collectionName, sort);
- }
- /// <summary>
- /// 查询索引最大的一条记录
- /// </summary>
- /// <typeparam name="T">该数据所属的类型</typeparam>
- /// <param name="query">查询的条件 可以为空</param>
- /// <param name="collectionName">去指定查询的集合</param>
- /// <param name="sort">排序字段</param>
- /// <returns>返回一个实体类型</returns>
- public T FindOneToIndexMax<T>(IMongoQuery query,string collectionName, string[] sort)
- {
- if (this._db == null)
- {
- return default(T);
- }
- try
- {
- MongoCollection<T> mc = this._db.GetCollection<T>(collectionName);
- query = this.InitQuery(query);
- T t = mc.Find(query).SetSortOrder(SortBy.Descending(sort)).FirstOrDefault<T>();
- return t;
- }
- catch (Exception ex)
- {
- return default(T);
- }
- }
- /// <summary>
- /// 查询一条记录
- /// </summary>
- /// <typeparam name="T">该数据所属的类型</typeparam>
- /// <param name="query">查询的条件 可以为空</param>
- /// <param name="collectionName">去指定查询的集合</param>
- /// <returns>返回一个实体类型</returns>
- public T FindOne<T>(IMongoQuery query, string collectionName)
- {
- if (this._db == null)
- {
- return default(T);
- }
- try
- {
- MongoCollection<T> mc = this._db.GetCollection<T>(collectionName);
- query = this.InitQuery(query);
- T t = mc.FindOne(query);
- return t;
- }
- catch (Exception ex)
- {
- return default(T);
- }
- }
- /// <summary>
- /// 查询一条记录
- /// </summary>
- /// <typeparam name="T">该数据所属的类型</typeparam>
- /// <param name="collectionName">去指定查询的集合</param>
- /// <returns>返回一个实体类型</returns>
- public T FindOne<T>(string collectionName)
- {
- return FindOne<T>(null, collectionName);
- }
- /// <summary>
- /// 查询一条记录
- /// </summary>
- /// <typeparam name="T">该数据所属的类型</typeparam>
- /// <returns>返回一个实体类型</returns>
- public T FindOne<T>()
- {
- string collectionName = typeof(T).Name;
- return FindOne<T>(null, collectionName);
- }
- /// <summary>
- /// 查询一条记录
- /// </summary>
- /// <typeparam name="T">该数据所属的类型</typeparam>
- /// <param name="query">查询的条件 可以为空</param>
- /// <returns>返回一个实体类型</returns>
- public T FindOne<T>(IMongoQuery query)
- {
- string collectionName = typeof(T).Name;
- return FindOne<T>(query, collectionName);
- }
- #endregion
- #region 普通的条件查询
- /// <summary>
- /// 根据指定条件查询集合中的数据
- /// </summary>
- /// <typeparam name="T">该集合数据的所属类型</typeparam>
- /// <param name="query">指定的查询条件 比如Query.And(Query.EQ("username","admin"),Query.EQ("password":"admin"))</param>
- /// <param name="collectionName">指定的集合的名称</param>
- /// <returns>返回一个List列表</returns>
- public List<T> Find<T>(IMongoQuery query, string collectionName)
- {
- if (this._db == null)
- {
- return null;
- }
- try
- {
- MongoCollection<T> mc = this._db.GetCollection<T>(collectionName);
- query = this.InitQuery(query);
- MongoCursor<T> mongoCursor = mc.Find(query);
- return mongoCursor.ToList<T>();
- }
- catch (Exception ex)
- {
- return null;
- }
- }
- /// <summary>
- /// 根据指定条件查询集合中的数据
- /// </summary>
- /// <typeparam name="T">该集合数据的所属类型</typeparam>
- /// <param name="query">指定的查询条件 比如Query.And(Query.EQ("username","admin"),Query.EQ("password":"admin"))</param>
- /// <returns>返回一个List列表</returns>
- public List<T> Find<T>(IMongoQuery query)
- {
- string collectionName = typeof(T).Name;
- return this.Find<T>(query,collectionName);
- }
- #endregion
- #region 分页查询 PageIndex和PageSize模式 在页数PageIndex大的情况下 效率明显变低
- /// <summary>
- /// 分页查询 PageIndex和PageSize模式 在页数PageIndex大的情况下 效率明显变低
- /// </summary>
- /// <typeparam name="T">所需查询的数据的实体类型</typeparam>
- /// <param name="query">查询的条件</param>
- /// <param name="pageIndex">当前的页数</param>
- /// <param name="pageSize">当前的尺寸</param>
- /// <param name="sortBy">排序方式</param>
- /// <param name="collectionName">集合名称</param>
- /// <returns>返回List列表</returns>
- public List<T> Find<T>(IMongoQuery query, int pageIndex, int pageSize, SortByDocument sortBy, string collectionName)
- {
- if (this._db == null)
- {
- return null;
- }
- try
- {
- MongoCollection<T> mc = this._db.GetCollection<T>(collectionName);
- MongoCursor<T> mongoCursor = null;
- query = this.InitQuery(query);
- sortBy = this.InitSortBy(sortBy, OBJECTID_KEY);
- //如页序号为0时初始化为1
- pageIndex = pageIndex == 0 ? 1 : pageIndex;
- //按条件查询 排序 跳数 取数
- mongoCursor = mc.Find(query).SetSortOrder(sortBy).SetSkip((pageIndex - 1) * pageSize).SetLimit(pageSize);
- return mongoCursor.ToList<T>();
- }
- catch (Exception ex)
- {
- return null;
- }
- }
- /// <summary>
- /// 分页查询 PageIndex和PageSize模式 在页数PageIndex大的情况下 效率明显变低
- /// </summary>
- /// <typeparam name="T">所需查询的数据的实体类型</typeparam>
- /// <param name="query">查询的条件</param>
- /// <param name="pageIndex">当前的页数</param>
- /// <param name="pageSize">当前的尺寸</param>
- /// <param name="sortBy">排序方式</param>
- /// <returns>返回List列表</returns>
- public List<T> Find<T>(IMongoQuery query, int pageIndex, int pageSize, SortByDocument sortBy)
- {
- string collectionName = typeof(T).Name;
- return this.Find<T>(query, pageIndex, pageSize, sortBy, collectionName);
- }
- #endregion
- #region 分页查询 指定索引最后项-PageSize模式
- /// <summary>
- /// 分页查询 指定索引最后项-PageSize模式
- /// </summary>
- /// <typeparam name="T">所需查询的数据的实体类型</typeparam>
- /// <param name="query">查询的条件 没有可以为null</param>
- /// <param name="indexName">索引名称</param>
- /// <param name="lastKeyValue">最后索引的值</param>
- /// <param name="pageSize">分页的尺寸</param>
- /// <param name="sortType">排序类型 1升序 -1降序 仅仅针对该索引</param>
- /// <param name="collectionName">指定的集合名称</param>
- /// <returns>返回一个List列表数据</returns>
- public List<T> Find<T>(IMongoQuery query, string indexName, object lastKeyValue, int pageSize, int sortType, string collectionName)
- {
- if (this._db == null)
- {
- return null;
- }
- try
- {
- MongoCollection<T> mc = this._db.GetCollection<T>(collectionName);
- MongoCursor<T> mongoCursor = null;
- query = this.InitQuery(query);
- //判断升降序后进行查询
- if (sortType > 0)
- {
- //升序
- if (lastKeyValue != null)
- {
- //有上一个主键的值传进来时才添加上一个主键的值的条件
- query = Query.And(query, Query.GT(indexName, BsonValue.Create(lastKeyValue)));
- }
- //先按条件查询 再排序 再取数
- mongoCursor = mc.Find(query).SetSortOrder(new SortByDocument(indexName, 1)).SetLimit(pageSize);
- }
- else
- {
- //降序
- if (lastKeyValue != null)
- {
- query = Query.And(query, Query.LT(indexName, BsonValue.Create(lastKeyValue)));
- }
- mongoCursor = mc.Find(query).SetSortOrder(new SortByDocument(indexName, -1)).SetLimit(pageSize);
- }
- return mongoCursor.ToList<T>();
- }
- catch (Exception ex)
- {
- return null;
- }
- }
- /// <summary>
- /// 分页查询 指定索引最后项-PageSize模式
- /// </summary>
- /// <typeparam name="T">所需查询的数据的实体类型</typeparam>
- /// <param name="query">查询的条件 没有可以为null</param>
- /// <param name="indexName">索引名称</param>
- /// <param name="lastKeyValue">最后索引的值</param>
- /// <param name="pageSize">分页的尺寸</param>
- /// <param name="sortType">排序类型 1升序 -1降序 仅仅针对该索引</param>
- /// <returns>返回一个List列表数据</returns>
- public List<T> Find<T>(IMongoQuery query, string indexName, object lastKeyValue, int pageSize, int sortType)
- {
- string collectionName = typeof(T).Name;
- return this.Find<T>(query, indexName, lastKeyValue, pageSize, sortType, collectionName);
- }
- /// <summary>
- /// 分页查询 指定ObjectId最后项-PageSize模式
- /// </summary>
- /// <typeparam name="T">所需查询的数据的实体类型</typeparam>
- /// <param name="query">查询的条件 没有可以为null</param>
- /// <param name="lastObjectId">上一条记录的ObjectId 没有可以为空</param>
- /// <param name="pageSize">每页尺寸</param>
- /// <param name="sortType">排序类型 1升序 -1降序 仅仅针对_id</param>
- /// <param name="collectionName">指定去查询集合的名称</param>
- /// <returns>返回一个List列表数据</returns>
- public List<T> Find<T>(IMongoQuery query, string lastObjectId, int pageSize, int sortType, string collectionName)
- {
- return this.Find<T>(query, OBJECTID_KEY, new ObjectId(lastObjectId), pageSize, sortType, collectionName);
- }
- /// <summary>
- /// 分页查询 指定ObjectId最后项-PageSize模式
- /// </summary>
- /// <typeparam name="T">所需查询的数据的实体类型</typeparam>
- /// <param name="query">查询的条件 没有可以为null</param>
- /// <param name="lastObjectId">上一条记录的ObjectId 没有可以为空</param>
- /// <param name="pageSize">每页尺寸</param>
- /// <param name="sortType">排序类型 1升序 -1降序 仅仅针对_id</param>
- /// <returns>返回一个List列表数据</returns>
- public List<T> Find<T>(IMongoQuery query, string lastObjectId, int pageSize, int sortType)
- {
- string collectionName = typeof(T).Name;
- return Find<T>(query, lastObjectId, pageSize, sortType, collectionName);
- }
- #endregion
- #endregion
- #region 更新数据
- /// <summary>
- /// 更新数据
- /// </summary>
- /// <typeparam name="T">更新的数据 所属的类型</typeparam>
- /// <param name="query">更新数据的查询</param>
- /// <param name="update">需要更新的文档</param>
- /// <param name="collectionName">指定更新集合的名称</param>
- public bool Update<T>(IMongoQuery query, IMongoUpdate update, string collectionName)
- {
- if (this._db == null)
- {
- return false;
- }
- try
- {
- MongoCollection<T> mc = this._db.GetCollection<T>(collectionName);
- query = this.InitQuery(query);
- //更新数据
- WriteConcernResult result = mc.Update(query, update, UpdateFlags.Multi);
- return true;
- }
- catch (Exception ex)
- {
- return false;
- }
- }
- /// <summary>
- /// 更新数据
- /// </summary>
- /// <typeparam name="T">更新的数据 所属的类型</typeparam>
- /// <param name="query">更新数据的查询</param>
- /// <param name="update">需要更新的文档</param>
- public bool Update<T>(IMongoQuery query, IMongoUpdate update)
- {
- string collectionName = typeof(T).Name;
- return this.Update<T>(query, update, collectionName);
- }
- #endregion
- #region 移除/删除数据
- /// <summary>
- /// 移除指定的数据
- /// </summary>
- /// <typeparam name="T">移除的数据类型</typeparam>
- /// <param name="query">移除的数据条件</param>
- /// <param name="collectionName">指定的集合名词</param>
- public bool Remove<T>(IMongoQuery query, string collectionName)
- {
- if (this._db == null)
- {
- return false;
- }
- try
- {
- MongoCollection<T> mc = this._db.GetCollection<T>(collectionName);
- query = this.InitQuery(query);
- //根据指定查询移除数据
- mc.Remove(query);
- return true;
- }
- catch (Exception ex)
- {
- return false;
- }
- }
- /// <summary>
- /// 移除指定的数据
- /// </summary>
- /// <typeparam name="T">移除的数据类型</typeparam>
- /// <param name="query">移除的数据条件</param>
- public bool Remove<T>(IMongoQuery query)
- {
- string collectionName = typeof(T).Name;
- return this.Remove<T>(query,collectionName);
- }
- /// <summary>
- /// 移除实体里面所有的数据
- /// </summary>
- /// <typeparam name="T">移除的数据类型</typeparam>
- public bool ReomveAll<T>()
- {
- string collectionName = typeof(T).Name;
- return this.Remove<T>(null,collectionName);
- }
- /// <summary>
- /// 移除实体里面所有的数据
- /// </summary>
- /// <typeparam name="T">移除的数据类型</typeparam>
- /// <param name="collectionName">指定的集合名称</param>
- public bool RemoveAll<T>(string collectionName)
- {
- return this.Remove<T>(null,collectionName);
- }
- #endregion
- #region 创建索引
- /// <summary>
- /// 创建索引
- /// </summary>
- /// <typeparam name="T">需要创建索引的实体类型</typeparam>
- public bool CreateIndex<T>()
- {
- if (this._db == null)
- {
- return false;
- }
- try
- {
- string collectionName = typeof(T).Name;
- MongoCollection<BsonDocument> mc = this._db.GetCollection<BsonDocument>(collectionName);
- PropertyInfo[] propertys = typeof(T).GetProperties(BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty);
- //得到该实体类型的属性
- foreach (PropertyInfo property in propertys)
- {
- //在各个属性中得到其特性
- foreach (object obj in property.GetCustomAttributes(true))
- {
- MongoDbFieldAttribute mongoField = obj as MongoDbFieldAttribute;
- if (mongoField != null)
- {// 此特性为mongodb的字段属性
- IndexKeysBuilder indexKey;
- if (mongoField.Ascending)
- {
- //升序 索引
- indexKey = IndexKeys.Ascending(property.Name);
- }
- else
- {
- //降序索引
- indexKey = IndexKeys.Descending(property.Name);
- }
- //创建该属性
- mc.CreateIndex(indexKey, IndexOptions.SetUnique(mongoField.Unique));
- }
- }
- }
- return true;
- }
- catch (Exception ex)
- {
- return false;
- }
- }
- #endregion
- #region 获取表的行数
- /// <summary>
- /// 获取数据表总行数
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="query"></param>
- /// <param name="collectionName"></param>
- /// <returns></returns>
- public long GetCount<T>(IMongoQuery query,string collectionName)
- {
- if (this._db == null)
- {
- return 0;
- }
- try
- {
- MongoCollection<T> mc = this._db.GetCollection<T>(collectionName);
- if (query == null)
- {
- return mc.Count();
- }
- else
- {
- return mc.Count(query);
- }
- }
- catch (Exception ex)
- {
- return 0;
- }
- }
- /// <summary>
- /// 获取数据表总行数
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="query"></param>
- /// <returns></returns>
- public long GetCount<T>(IMongoQuery query)
- {
- string collectionName = typeof(T).Name;
- return GetCount<T>(query,collectionName);
- }
- #endregion
- #region 获取集合的存储大小
- /// <summary>
- /// 获取集合的存储大小
- /// </summary>
- /// <typeparam name="T">该集合对应的实体类</typeparam>
- /// <returns>返回一个long型</returns>
- public long GetDataSize<T>()
- {
- string collectionName = typeof(T).Name;
- return GetDataSize(collectionName);
- }
- /// <summary>
- /// 获取集合的存储大小
- /// </summary>
- /// <param name="collectionName">该集合对应的名称</param>
- /// <returns>返回一个long型</returns>
- public long GetDataSize(string collectionName)
- {
- if (this._db == null)
- {
- return 0;
- }
- try
- {
- MongoCollection<BsonDocument> mc = this._db.GetCollection<BsonDocument>(collectionName);
- return mc.GetTotalStorageSize();
- }
- catch (Exception ex)
- {
- return 0;
- }
- }
- #endregion
- #region 私有的一些辅助方法
- /// <summary>
- /// 初始化查询记录 主要当该查询条件为空时 会附加一个恒真的查询条件,防止空查询报错
- /// </summary>
- /// <param name="query">查询的条件</param>
- /// <returns></returns>
- private IMongoQuery InitQuery(IMongoQuery query)
- {
- if (query == null)
- {
- //当查询为空时 附加恒真的条件 类似SQL:1=1的语法
- query = Query.Exists(OBJECTID_KEY);
- }
- return query;
- }
- /// <summary>
- /// 初始化排序条件 主要当条件为空时 会默认以ObjectId递增的一个排序
- /// </summary>
- /// <param name="sortBy"></param>
- /// <param name="sortByName"></param>
- /// <returns></returns>
- private SortByDocument InitSortBy(SortByDocument sortBy, string sortByName)
- {
- if (sortBy == null)
- {
- //默认ObjectId 递增
- sortBy = new SortByDocument(sortByName, -1);
- }
- return sortBy;
- }
- private UpdateDocument InitUpdateDocument(UpdateDocument update,string indexName)
- {
- if (update == null)
- {
- update = new UpdateDocument("$inc", new QueryDocument(indexName, 0));
- }
- return update;
- }
- #endregion
- }
- }
4.调用:先引用库文件:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using MongoDB;
- using MongoDbDemo;
- using MongoDB.Driver;
- using MongoDB.Bson;
- using DAL.Entity;
- using DAL;
- using MongoDB.Driver.Builders;
- using System.Diagnostics;
- namespace MongoDbDemo.Controllers
- {
- public class HomeController : Controller
- {
- //
- // GET: /Home/
- public ActionResult Index()
- {
- return Content("MongoDbDemo");
- }
- #region INSERT
- /// <summary>
- /// 添加用户
- /// </summary>
- /// <returns></returns>
- public ActionResult Ruser()
- {
- try
- {
- string name = Request["name"];
- string age = Request["age"];
- User user1 = new User { Uname = name, Age = age };
- MongoDbHelper mh = new MongoDbHelper("127.0.0.1", "1000");
- if (mh.Insert<User>(user1))
- {
- return Json(new { success = "true" });
- }
- }
- catch (Exception)
- {
- return Json(new { success = "filled" });
- throw;
- }
- return Json(new { success = "filled" });
- }
- #endregion
- #region SELECT
- /// <summary>
- /// 查询一个集合中的所有数据
- /// </summary>
- /// <returns></returns>
- public ActionResult Seluser()
- {
- MongoDbHelper mh = new MongoDbHelper("127.0.0.1", "1000");
- List<User> users = mh.FindAll<User>();
- return Json(new { success="true"});
- }
- /// <summary>
- /// 按条件查询一条数据
- /// </summary>
- /// <returns></returns>
- public ActionResult SelOne()
- {
- string name = Request["name"];
- string age=Request["age"];
- MongoDbHelper mh = new MongoDbHelper("127.0.0.1", "1000");
- User users = mh.FindOne<User>(Query.And(Query.EQ("Uname", name), Query.EQ("Age", age)));
- return Json(new {success="true" ,users=users});
- }
- /// <summary>
- /// 分页查询
- /// </summary>
- /// <returns></returns>
- public ActionResult SelPage()
- {
- int pageindex=int.Parse(Request["pageindex"]);//页索引
- int pagesize = int.Parse(Request["pagesize"]);//行数
- MongoDbHelper mh = new MongoDbHelper("127.0.0.1", "1000");
- Stopwatch sw1 = new Stopwatch();
- sw1.Start();
- List<User> users = mh.Find<User>(null,pageindex,pagesize,null);
- return Json(new {success="true",users=users });
- }
- #endregion
- #region UPDATE
- /// <summary>
- /// 修改信息
- /// </summary>
- /// <returns></returns>
- public ActionResult upduser()
- {
- MongoDbHelper mh = new MongoDbHelper("127.0.0.1", "1000");
- if (mh.Update<User>(Query.EQ("Uname", "阿斯达"), Update.Set("Uname", "阿斯达s"), "User"))
- {
- return Json(new { success = "true" });
- }
- else
- {
- return Json(new { success = "fales" });
- }
- }
- #endregion
- #region DELETE
- /// <summary>
- /// 删除消息
- /// </summary>
- /// <returns></returns>
- public ActionResult deluser()
- {
- MongoDbHelper mh = new MongoDbHelper("127.0.0.1", "1000");
- if (mh.Remove<User>(Query.EQ("Uname", "阿斯达s")))
- {
- return Json(new { success = "true" });
- }
- else {
- return Json(new { success = "fales" });
- }
- }
- #endregion
- }
- }
简单的使用.NET 进行MongoDB的增删改查。
【MongoDB学习-在.NET中的简单操作】的更多相关文章
- MongoDB学习-在.NET中的简单操作
1.新建MVC项目, 管理NuGet包,进入下载MongDB.net库文件 2.新增项目DAL数据访问层,引用以下库文件: 3.C# 访问MongoDB通用方法类: using MongoDB.Dri ...
- 【MongoDB学习-在.NET中的简单操作类】
1.新建MVC项目, 管理NuGet包,进入下载MongDB.net库文件 2.新增项目DAL数据访问层,引用以下库文件: 3.C# 访问MongoDB通用方法类: using MongoDB.Dri ...
- C# 对MongoDB 进行增删改查的简单操作
C# 对MongoDB 进行增删改查的简单操作 下面演示下C#操作MongoDB驱动的简单的增删改查代码 运用到的MongoDB支持的C#驱动,当前版本为1.6.0 1,连接数据库 /// & ...
- 使用Flask+MongoDB实现基于REST的接口简单操作
目录 前言 1 准备工作 2 具体实现 前言 最近在捣鼓如何使用阿里云服务器搭建一个简单的基于Flask框架的后端接口,刚开始为了图方便,就直接买了一个Windows Server 2008系统服务器 ...
- MongoDB学习(1)--安装,基本curd操作
知识点: 1-MongoDB 安装,启动和卸载 2-基本概念 3-基本的增删改查操作(CURD) 来回顾总结一把学习的mongodb,如果有javascript基础,学习"芒果DB" ...
- iOS学习之UITableView中Cell的操作
接着iOS学习之Table View的简单使用 这篇,这里主要讲UITableView 中的Cell的操作,包括标记.移动.删除.插入. 为了简单快捷,直接从原来那篇的代码开始,代码下载地址:http ...
- Python学习笔记3-文件的简单操作
Python中的文件操作 Python中文件打操作离不开两个模块 os 和 shutil os:操作文件.目录: Python os模块包含普遍的操作系统功能.如果你希望你的程序能够与平台无关的话, ...
- JavaWeb学习笔记——jquery中的dom操作
jquery中的dom操作 废话不说:直接上例子: 1.添加节点-html页面 Append:向每个匹配的元素内部追加内容. <body> <ul id="city& ...
- Python框架学习之Flask中的数据库操作
数据库操作在web开发中扮演着一个很重要的角色,网站中很多重要的信息都需要保存到数据库中.如用户名.密码等等其他信息.Django框架是一个基于MVT思想的框架,也就是说他本身就已经封装了Model类 ...
随机推荐
- csdn 不登录浏览全文 chrome 浏览器
1将此文章存到书签栏. 2 右键点击保存到书签栏的这个书签,然后点击修改. 3 名称改为:CSDN查看全文,网址改为: javascript:$("#article_content" ...
- bootstrap基础学习(四)——网格系统(列的偏移、排序、嵌套)
网格系统——列偏移.列排序.列嵌套 列偏移:有的时候,我们不希望相邻的两个列紧靠在一起,但又不想使用margin或者其他的技术手段来.这个时候就可以使用列偏移(offset)功能来实现.使用列偏移也非 ...
- win10 开机背景图
地址 C:\Users\*\AppData\Local\Packages\Microsoft.Windows.ContentDeliveryManager_cw5n1h2txyewy\LocalSta ...
- .NET Core中使用EF Core连接MySQL
最近一直在捣鼓.NET Core方面的东西,顺便写下点东西记录下 1.打开vs2017,新建一个项目 2.vs会自动生成一个项目,然后打开NuGet搜索MySql.Data.EntityFramewo ...
- 跟着刚哥学习Spring框架--通过XML方式配置Bean(三)
Spring配置Bean有两种形式(XML和注解) 今天我们学习通过XML方式配置Bean 1. Bean的配置方式 通过全类名(反射)的方式 √ id:标识容器中的bean.id唯一. √ cl ...
- nginx官方文档 之 http负载均衡 学习笔记
一.负载均衡 算法 大致可以分两类: (1)不能保证用户的每一次请求都通过负载均衡到达同一服务器. (2)可保证用户的每一次请求都通过负载均衡到达同一服务器. 第二类的应用场景: 1.如果服务器有缓存 ...
- JS生成某个范围的随机数【四种情况详解】
JS没有现成的函数,能够直接生成指定范围的随机数. 但是它有个函数:Math.random() 这个函数可以生成 [0,1) 的一个随机数. 利用它,我们就可以生成指定范围内的随机数. 而涉及范围的 ...
- http://www.vaikan.com/docs/jquery.form.plugin/jquery.form.plugin.html#getting-started
http://www.vaikan.com/docs/jquery.form.plugin/jquery.form.plugin.html#getting-started Jquery.Form 异步 ...
- Shell - 简明Shell入门04 - 判断语句(If)
示例脚本及注释 #!/bin/bash var=$1 # 将脚本的第一个参数赋值给变量var if test $var # test - check file types and compare va ...
- POJ 2405
#include <iostream> #include <cmath> #include <iomanip> #define pi 3.1415926536 us ...