C# 访问MongoDB 通用方法类

using MongoDB.Driver;  
using System;  namespace MongoDBDemo  
{  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 MongoDBDemo 
{  /// <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 MongoDBDemo  
{  /// <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  }  
}  
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  }  
}  

 

Query.All("name", "a","b"); //通过多个元素来匹配数组

 Query.And(Query.EQ("name","a"), Query.EQ("title", "t"));//同时满足多个条件

 Query.EQ("name", "a");//等于

 Query.Exists("type", true);//判断键值是否存在

 Query.GT("value", 2);//大于>

 Query.GTE("value", 3);//大于等于>=

 Query.In("name", "a","b");//包括指定的所有值,可以指定不同类型的条件和值

 Query.LT("value", 9);//小于<

 Query.LTE("value", 8);//小于等于<=

 Query.Mod("value", 3, 1);//将查询值除以第一个给定值,若余数等于第二个给定值则返回该结果

 Query.NE("name", "c");//不等于

 Query.Nor(Array);//不包括数组中的值

 Query.Not("name");//元素条件语句

 Query.NotIn("name", "a",2);//返回与数组中所有条件都不匹配的文档

 Query.Or(Query.EQ("name","a"), Query.EQ("title", "t"));//满足其中一个条件

 Query.Size("name", 2);//给定键的长度

 Query.Type("_id", BsonType.ObjectId);//给定键的类型

 Query.Where(BsonJavaScript);//执行JavaScript

 Query.Matches("Title",str);//模糊查询 相当于sql中like -- str可包含正则表达式

 

网上找的,写的不错,收藏了,简单的使用.NET 进行MongoDB的增删改查

转载于:https://www.cnblogs.com/Luouy/p/6098901.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/371974.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

html网页背景图片平铺代码,jQuery图片平铺效果制作网页背景图片平铺代码

插件描述&#xff1a;jQuery图片平铺效果制作网页背景图片平铺代码调用JS文件调用插件方法$(function(){// 插件初始化$(img).jqthumb({classname : jqthumb, // 类名. 默认是 jqthumbwidth : 100%, // 新的图像裁剪后宽度. 默认是 100px.height : 100%, // 新的图像裁剪后高度…

使用保险丝结构管理MQ和ESB的大型部署,第I部分

FuseSource最近发布了ActiveMQ和ServiceMix发行版的企业版。 其中一些重要功能包括增量修补 &#xff0c; 自定义平台安装程序和第三方验证 。 新企业版附带的最酷的功能之一是Fuse Fabric和一些新工具 &#xff0c;使您可以利用Fabric管理环境。 Fabric允许您通过一些命令行或…

Mybatis参数传递及返回类型

mybatis参数传递&#xff1a; 单个参数&#xff1a;不做特殊处理 #{参数名}&#xff1a;取出参数值 多个参数&#xff1a;做特殊处理 多个参数会被封装成一个map key&#xff1a;param1 ... paramN value&#xff1a;传入的参数…

网络html代码是什么问题,html代码问题

html代码问题來源:互聯網 2010-03-22 10:35:57 評論分類: 電腦/網絡 >> 程序設計 >> 其他編程語言問題描述:这三种链接格式我都试了&#xff0c;都不行&#xff0c;请高手指点下。。。。。注意&#xff1a;我要的是代码&#xff0c;不是操作方法&#xff0c;因为…

spring mvc 文件上传

spring mvc 文件上传 一、单文件上传 配置步骤&#xff1a; 步骤一、在配置文件中配置包扫描器&#xff08;暂且这样配&#xff0c;会出问题&#xff0c;我们下面说解决方案&#xff09; <?xml version"1.0" encoding"UTF-8"?> <beans xmlns…

使用工厂模式解决设计问题

工厂设计模式是面向对象环境中最常用的模式之一。 再次来自“创意设计”模式类别&#xff0c;即有关对象创建的所有信息。 在某些情况下&#xff0c;对象的创建很复杂&#xff0c;可能需要某种程度的抽象&#xff0c;以便客户端代码无法意识到这些复杂性和内部实现细节。 在某些…

103. Binary Tree Zigzag Level Order Traversal

二刷。 BFS&#xff0c;基本习惯上用Iterative的做法来做&#xff0c;就是QUEUE。 /*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val x; }* }*/ public class Solution…

java多线程系列13 设计模式 Future 模式

Future 模式 类似于ajax请求 页面异步的进行后台请求 用户无需等待请求的结果 就可以继续浏览或者操作 核心就是&#xff1a;去除了主函数的等待时间&#xff0c;并使得原本需要等待的时间段可以用于处理其他业务逻辑 JDK内置实现Future模式演示一下 public class RealData im…

lodop转到其他html页面,Lodop实现打印功能

思路&#xff1a;1、在 html 页面引入 LodopFuncs.js 文件&#xff0c;并用 object 标签和 embed 标签获取 lodop 对象2、在 js 中获取 html 页面中的 object 和 embed 对象&#xff0c;并使用getLodop() 方法得到 lodop 对象3、实现打印功能&#xff0c;以下三步是必需的初始化…

完整的Web应用程序Tomcat JSF Primefaces JPA Hibernate –第3部分

Primefaces AutoComplete&#xff0c;JSF转换器 这篇文章从第一部分和第二部分继续。 JSF拥有Converter工具&#xff0c;可以帮助我们从用户视图中获取一些数据并将其转换为从数据库或缓存中加载的对象。 在“ com.converter”包中&#xff0c;创建以下类&#xff1a; packa…

html5首屏加载乐山暴雨,发布前端项目时因chunk-vendors过大导致首屏加载太慢,Vue Build时chunk-vendors的优化方案...

这个优化是两方面的&#xff0c;前端将文件打包成.gz文件&#xff0c;然后通过nginx的配置&#xff0c;让浏览器直接解析.gz文件。1、compression-webpack-plugin插件打包.gz文件安装插件npm install --save-dev compression-webpack-plugin或者yarn add compression-webpack-p…

width:100vh与min-height:calc(100vh + 51px)

vh:相对于视窗的高度&#xff0c;那么vw:则是相对于视窗的高度。 “视区”所指为浏览器内部的可视区域大小&#xff0c;即window.innerWidth/window.innerHeight大小&#xff0c;不包含任务栏标题栏以及底部工具栏的浏览器区域大小。 详细vh的用法&#xff0c;大家可以参考http…

XML配置文件中的Spring配置文件

我的上一个博客非常简单&#xff0c;因为它涵盖了我从Spring 3.0.x到Spring 3.1.x的轻松升级&#xff0c;最后我提到可以将Spring模式升级到3.1&#xff0c;以利用Spring的最新功能。 在今天的博客中&#xff0c;我将介绍这些功能中最酷的功能之一&#xff1a;Spring配置文件。…

交大计算机专业怎样,计算机专业高校实力排名,上海交大第五,清华第二,第一毫无争议...

原标题&#xff1a;计算机专业高校实力排名&#xff0c;上海交大第五&#xff0c;清华第二&#xff0c;第一毫无争议计算机专业在近几年可谓是“大热”&#xff0c;众多考生抢破头也想当码农&#xff0c;背后的原因其实不难理解。互联网时代的到来&#xff0c;计算机早已渗透到…

python_day7 绑定方法与非绑定方法

在类中定义函数如果 不加装饰器 则默认 为对象作为绑定方法 如果增加 classmethod 是 以 类 作为绑定方法 增加 classmethod 是 非绑定方法&#xff0c;就是不将函数 绑定 ##################### class Foo: def func(self): print(self) classmethod def func…

Spring Security使用Hibernate实现自定义UserDetails

大多数时候&#xff0c;我们将需要在Web应用程序中配置自己的安全访问角色。 这在Spring Security中很容易实现。 在本文中&#xff0c;我们将看到最简单的方法。 首先&#xff0c;我们将在数据库中需要以下表格&#xff1a; CREATE TABLE IF NOT EXISTS mydb.security_role (…

python之路-面向对象

编程范式 编程是 程序 员 用特定的语法数据结构算法组成的代码来告诉计算机如何执行任务的过程 &#xff0c; 一个程序是程序员为了得到一个任务结果而编写的一组指令的集合&#xff0c;正所谓条条大路通罗马&#xff0c;实现一个任务的方式有很多种不同的方式&#xff0c; 对这…

西安邮电大学计算机科学与技术有专硕吗,2020年西安邮电大学计算机学院考研拟录取名单及排名!...

20考研复试调剂群&#xff1a;4197552812020年西安邮电大学计算机学院硕士研究生招生复试成绩及综合排名各位考生&#xff1a;现将我院2020年硕士研究生招生复试成绩及综合排名公布(最终录取名单及新生学籍注册均以“全国硕士研究生招生信息公开平台”备案信息为准)&#xff0c…

用Java排序的五种有用方法

Java排序快速概述&#xff1a; 正常的列表&#xff1a; private static List VEGETABLES Arrays.asList("apple", "cocumbers", "blackberry");Collections.sort(VEGETABLES);output: apple, blackberry, cocumbers反向排序&#xff1a; pri…

[python]-数据科学库Numpy学习

一、Numpy简介&#xff1a; Python中用列表(list)保存一组值&#xff0c;可以用来当作数组使用&#xff0c;不过由于列表的元素可以是任何对象&#xff0c;因此列表中所保存的是对象的指针。这样为了保存一个简单的[1,2,3]&#xff0c;需要有3个指针和三个整数对象。对于数值运…