-
【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;
- }
-
-
-
-
- private readonly string MONGO_CONN_HOST;
-
-
-
-
- private readonly int MONGO_CONN_PORT = 27017;
-
-
-
-
- private readonly string CONNECT_TIME_OUT;
-
-
-
-
- private readonly string DB_NAME = "Mdemo";
-
-
-
-
-
- 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);
-
- 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
- {
-
-
-
- [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
- public class MongoDbFieldAttribute : Attribute
- {
-
-
-
- public bool IsIndex { get; set; }
-
-
-
-
- public bool Unique { get; set; }
-
-
-
-
- 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
- {
-
-
-
- public class MongoDbHelper
- {
-
-
-
- private MongoDatabase _db;
-
-
-
-
- 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 插入数据
-
-
-
-
-
- public bool Insert<T>(T t)
- {
-
- string collectionName = typeof(T).Name;
- return Insert<T>(t, collectionName);
- }
-
-
-
-
-
-
-
- public bool Insert<T>(T t, string collectionName)
- {
- if (this._db == null)
- {
- return false;
- }
- try
- {
- MongoCollection<BsonDocument> mc = this._db.GetCollection<BsonDocument>(collectionName);
-
- BsonDocument bd = t.ToBsonDocument();
-
- WriteConcernResult result = mc.Insert(bd);
- if (!string.IsNullOrEmpty(result.ErrorMessage))
- {
- return false;
- }
- return true;
- }
- catch (Exception ex)
- {
- return false;
- }
- }
-
-
-
-
-
-
- public bool Insert<T>(List<T> list)
- {
-
- string collectionName = typeof(T).Name;
- return this.Insert<T>(list, collectionName);
- }
-
-
-
-
-
-
-
- public bool Insert<T>(List<T> list, string collectionName)
- {
- if (this._db == null)
- {
- return false;
- }
- try
- {
- MongoCollection<BsonDocument> mc = this._db.GetCollection<BsonDocument>(collectionName);
-
- List<BsonDocument> bsonList = new List<BsonDocument>();
-
- list.ForEach(t => bsonList.Add(t.ToBsonDocument()));
-
- mc.InsertBatch(bsonList);
- return true;
- }
- catch (Exception ex)
- {
- return false;
- }
- }
- #endregion
-
- #region 查询数据
-
- #region 查询所有记录
-
-
-
-
-
-
- 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();
-
- return mongoCursor.ToList<T>();
- }
- catch (Exception ex)
- {
- return null;
- }
- }
-
-
-
-
-
-
- public List<T> FindAll<T>()
- {
- string collectionName = typeof(T).Name;
- return FindAll<T>(collectionName);
- }
- #endregion
-
- #region 查询一条记录
-
-
-
-
-
-
-
- public T FindOneToIndexMax<T>(string collectionName, string[] sort)
- {
- return FindOneToIndexMax<T>(null, collectionName, sort);
- }
-
-
-
-
-
-
-
-
-
- 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);
- }
- }
-
-
-
-
-
-
-
- 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);
- }
- }
-
-
-
-
-
-
-
- public T FindOne<T>(string collectionName)
- {
- return FindOne<T>(null, collectionName);
- }
-
-
-
-
-
-
- public T FindOne<T>()
- {
- string collectionName = typeof(T).Name;
- return FindOne<T>(null, collectionName);
- }
-
-
-
-
-
-
-
-
- public T FindOne<T>(IMongoQuery query)
- {
- string collectionName = typeof(T).Name;
- return FindOne<T>(query, collectionName);
- }
- #endregion
-
- #region 普通的条件查询
-
-
-
-
-
-
-
- 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;
- }
- }
-
-
-
-
-
-
-
- public List<T> Find<T>(IMongoQuery query)
- {
- string collectionName = typeof(T).Name;
- return this.Find<T>(query,collectionName);
- }
- #endregion
-
- #region 分页查询 PageIndex和PageSize模式 在页数PageIndex大的情况下 效率明显变低
-
-
-
-
-
-
-
-
-
-
-
- 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);
-
- 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;
- }
- }
-
-
-
-
-
-
-
-
-
-
- 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模式
-
-
-
-
-
-
-
-
-
-
-
-
- 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;
- }
- }
-
-
-
-
-
-
-
-
-
-
-
- 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);
- }
-
-
-
-
-
-
-
-
-
-
-
- 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);
- }
-
-
-
-
-
-
-
-
-
-
- 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 更新数据
-
-
-
-
-
-
-
-
- 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;
- }
- }
-
-
-
-
-
-
-
- public bool Update<T>(IMongoQuery query, IMongoUpdate update)
- {
- string collectionName = typeof(T).Name;
- return this.Update<T>(query, update, collectionName);
- }
-
- #endregion
-
- #region 移除/删除数据
-
-
-
-
-
-
- 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;
- }
- }
-
-
-
-
-
-
- public bool Remove<T>(IMongoQuery query)
- {
- string collectionName = typeof(T).Name;
- return this.Remove<T>(query,collectionName);
- }
-
-
-
-
-
- public bool ReomveAll<T>()
- {
- string collectionName = typeof(T).Name;
- return this.Remove<T>(null,collectionName);
- }
-
-
-
-
-
-
- public bool RemoveAll<T>(string collectionName)
- {
- return this.Remove<T>(null,collectionName);
- }
- #endregion
-
- #region 创建索引
-
-
-
-
- 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)
- {
-
- 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 获取表的行数
-
-
-
-
-
-
-
- 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;
- }
- }
-
-
-
-
-
-
- public long GetCount<T>(IMongoQuery query)
- {
- string collectionName = typeof(T).Name;
- return GetCount<T>(query,collectionName);
- }
-
- #endregion
-
- #region 获取集合的存储大小
-
-
-
-
-
- public long GetDataSize<T>()
- {
- string collectionName = typeof(T).Name;
- return GetDataSize(collectionName);
- }
-
-
-
-
-
-
- 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 私有的一些辅助方法
-
-
-
-
-
- private IMongoQuery InitQuery(IMongoQuery query)
- {
- if (query == null)
- {
-
- query = Query.Exists(OBJECTID_KEY);
- }
- return query;
- }
-
-
-
-
-
-
-
- private SortByDocument InitSortBy(SortByDocument sortBy, string sortByName)
- {
- if (sortBy == null)
- {
-
- 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
- {
-
-
-
- public ActionResult Index()
- {
- return Content("MongoDbDemo");
- }
-
- #region INSERT
-
-
-
-
- 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
-
-
-
-
- public ActionResult Seluser()
- {
- MongoDbHelper mh = new MongoDbHelper("127.0.0.1", "1000");
- List<User> users = mh.FindAll<User>();
- return Json(new { success="true"});
- }
-
-
-
-
-
- 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});
- }
-
-
-
-
-
- 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
-
-
-
-
- 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
-
-
-
-
- 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的增删改查。
-
相关阅读:
list()
Python 数据类型转换
设计模式 — 代理模式(静态代理、动态代理、Cglib代理) 转载
java线程池实现原理
HashMap深度解析(转载) jdk1.7
Java Serializable 序列化和反序列化 (转载)
Java遍历HashMap并修改(remove)(转载)
Java中的break,continue关于标签的用法(转载)
遍历List过程中删除操作报java.util.ConcurrentModificationException错误
java Date时间的各种转换方式和Mysql存时间类型字段的分析
-
原文地址:https://www.cnblogs.com/jjg0519/p/6733044.html
Copyright © 2020-2023
润新知