MongoDB的C#封装类
代码:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using MongoDB; using MongoDB.GridFS; namespace CompanyName.DepartmentName.Common.Util { public class MongoHelper { public static readonly string connectionString = "Servers=127.0.0.1:2222;ConnectTimeout=30000;ConnectionLifetime=300000;MinimumPoolSize=8;MaximumPoolSize=256;Pooled=true"; public static readonly string database = "DiDiDataBase"; #region 新增 /// <summary> /// 插入新数据 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="collectionName"></param> /// <param name="entiry"></param> public static void InsertOne<T>(string collectionName, T entity) where T : class { using (Mongo mongo = new Mongo(connectionString)) { mongo.Connect(); IMongoDatabase friends = mongo.GetDatabase(database); IMongoCollection<T> categories = friends.GetCollection<T>(collectionName); categories.Insert(entity, true); mongo.Disconnect(); } } /// <summary> /// 插入多个数据 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="collectionName"></param> /// <param name="entiry"></param> public static void InsertAll<T>(string collectionName, IEnumerable<T> entity) where T : class { using (Mongo mongo = new Mongo(connectionString)) { mongo.Connect(); IMongoDatabase friends = mongo.GetDatabase(database); IMongoCollection<T> categories = friends.GetCollection<T>(collectionName); categories.Insert(entity, true); mongo.Disconnect(); } } #endregion #region 更新 /// <summary> /// 更新操作 /// </summary> /// <typeparam name="T">类型</typeparam> /// <param name="collectionName">表名</param> /// <param name="query">条件</param> /// <param name="entry">新实体</param> public static void Update<T>(string collectionName, Document entity, Document query) where T : class { using (Mongo mongo = new Mongo(connectionString)) { mongo.Connect(); IMongoDatabase friends = mongo.GetDatabase(database); IMongoCollection<T> categories = friends.GetCollection<T>(collectionName); categories.Update(entity, query, true); mongo.Disconnect(); } } /// <summary> /// 更新操作 /// </summary> /// <typeparam name="T">类型</typeparam> /// <param name="collectionName">表名</param> /// <param name="query">条件</param> /// <param name="entry">新实体</param> public static void UpdateAll<T>(string collectionName, Document entity, Document query) where T : class { using (Mongo mongo = new Mongo(connectionString)) { mongo.Connect(); IMongoDatabase friends = mongo.GetDatabase(database); IMongoCollection<T> categories = friends.GetCollection<T>(collectionName); categories.Update(entity, query, UpdateFlags.MultiUpdate, true); mongo.Disconnect(); } } #endregion #region 查询 /// <summary> /// 获取一条数据 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="collectionName"></param> /// <param name="query"></param> /// <returns></returns> public static T GetOne<T>(string collectionName, Document query) where T : class { T result = default(T); using (Mongo mongo = new Mongo(connectionString)) { mongo.Connect(); IMongoDatabase friends = mongo.GetDatabase(database); IMongoCollection<T> categories = friends.GetCollection<T>(collectionName); result = categories.FindOne(query); mongo.Disconnect(); } return result; } /// <summary> /// 获取一条数据 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="collectionName"></param> /// <param name="query"></param> /// <returns></returns> public static T GetOne<T>(string collectionName, Document query, Document fields) where T : class { T result = default(T); using (Mongo mongo = new Mongo(connectionString)) { mongo.Connect(); IMongoDatabase friends = mongo.GetDatabase(database); IMongoCollection<T> categories = friends.GetCollection<T>(collectionName); result = categories.Find(query, fields).Skip(0).Limit(1).Documents.First(); mongo.Disconnect(); } return result; } /// <summary> /// 获取一个集合下所有数据 /// </summary> /// <param name="collectionName"></param> /// <returns></returns> public static List<T> GetAll<T>(string collectionName) where T : class { List<T> result = new List<T>(); using (Mongo mongo = new Mongo(connectionString)) { mongo.Connect(); IMongoDatabase friends = mongo.GetDatabase(database); IMongoCollection<T> categories = friends.GetCollection<T>(collectionName); foreach (T entity in categories.FindAll().Limit(50).Documents) { result.Add(entity); } mongo.Disconnect(); } return result; } /// <summary> /// 获取列表 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="collectionName"></param> /// <param name="query"></param> /// <param name="Sort"></param> /// <param name="cp"></param> /// <param name="mp"></param> /// <returns></returns> public static List<T> GetList<T>(string collectionName, object selector, Document sort, int cp, int mp) where T : class { List<T> result = new List<T>(); using (Mongo mongo = new Mongo(connectionString)) { mongo.Connect(); IMongoDatabase friends = mongo.GetDatabase(database); IMongoCollection<T> categories = friends.GetCollection<T>(collectionName); foreach (T entity in categories.Find(selector).Sort(sort).Skip((cp - 1) * mp).Limit(mp).Documents) { result.Add(entity); } mongo.Disconnect(); } return result; } /// <summary> /// 获取列表 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="collectionName"></param> /// <param name="query"></param> /// <param name="Sort"></param> /// <param name="cp"></param> /// <param name="mp"></param> /// <returns></returns> public static List<T> GetList<T>(string collectionName, object selector, object fields, Document sort, int cp, int mp) where T : class { List<T> result = new List<T>(); using (Mongo mongo = new Mongo(connectionString)) { mongo.Connect(); IMongoDatabase friends = mongo.GetDatabase(database); IMongoCollection<T> categories = friends.GetCollection<T>(collectionName); foreach (T entity in categories.Find(selector, fields).Sort(sort).Skip((cp - 1) * mp).Limit(mp).Documents) { result.Add(entity); } mongo.Disconnect(); } return result; } #endregion #region 删除 /// <summary> /// 删除数据 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="collectionName"></param> /// <param name="entity"></param> public static void Delete<T>(string collectionName, Document query) where T : class { using (Mongo mongo = new Mongo(connectionString)) { mongo.Connect(); IMongoDatabase friends = mongo.GetDatabase(database); IMongoCollection<T> categories = friends.GetCollection<T>(collectionName); categories.Remove(query, true); mongo.Disconnect(); } } #endregion } }
添加索引:
db.T_OrderInfo.ensureIndex( { OriginPoint : "2dsphere" ,TerminalPoint:"2dsphere" } )
查找距离为附近为1公里的点
db.T_OrderInfo.find( { OriginPoint: { $near : { $geometry : { type : "Point" , coordinates : [122.5323811111,52.96887811111]}, $maxDistance :1/111.12 }}})
添加一个方法:
/// <summary> /// 获取一个通过查询条件的集合下所有数据 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="collectionName"></param> /// <param name="query"></param> /// <returns></returns> public static List<T> GetList<T>(string collectionName, object query) where T : class { List<T> result = new List<T>(); using (Mongo mongo = new Mongo(connectionString)) { mongo.Connect(); IMongoDatabase friends = mongo.GetDatabase(database); IMongoCollection<T> categories = friends.GetCollection<T>(collectionName); foreach (T entity in categories.Find(query).Skip(0).Limit(100).Documents) { result.Add(entity); } mongo.Disconnect(); } return result; }
//var doc = new Document(); //doc.Add("OriginName", "大起点"); //var info = MongoHelper.GetList<OrderInfo>("T_OrderInfo", doc); var doc = new Document(); List<double> doub = new List<double>(); doub.Add(122.5323811111); doub.Add(52.96887811111); //doc.Add("OriginPoint", new Document("$near", new Document("$geometry", new Document("type", "Point").Append("coordinates", doub)).Append("$maxDistance",1))); doc.Add("OriginPoint", new Document("$near", new Document("$geometry", new Document("type", "Point").Append("coordinates", new double[] { 122.5323811111, 52.96887811111 })).Append("$maxDistance", 1/111.12))); var infoList2 = MongoHelper.GetList<OrderInfo>("T_OrderInfo", doc);
这样可以查询相近的地理位置
组合索引:
db.T_OrderInfo.ensureIndex( {ActiveTime:-1, OriginPoint : "2dsphere" ,TerminalPoint:"2dsphere" } )
添加50万条测试数据
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using CompanyName.DepartmentName.Common.Util; using MongoDB; using MongoDB.GridFS; namespace Console.Test { class Program { static void Main(string[] args) { Random ran = new Random(); double bnn = 122.5; double enn = 52.9; double tbnn = 113.3; double tenn = 23.1; DateTime dt = DateTime.Now; for (var i = 1; i < 500001; i++) { //起点坐标 var bn = Convert.ToDouble(bnn.ToString() + ran.Next(1000000, 9999999).ToString()); var en = Convert.ToDouble(enn.ToString() + ran.Next(1000000, 9999999).ToString()); //终点坐标 var tbn = Convert.ToDouble(tbnn.ToString() + ran.Next(1000000, 9999999).ToString()); var ten = Convert.ToDouble(tenn.ToString() + ran.Next(1000000, 9999999).ToString()); //时间 var dtt = dt.AddMinutes(ran.Next(-100000, 100000)); //System.Console.WriteLine(bn + "||" + en + "||" + dtt.ToString("yyyy-MM-dd HH:mm:ss")); OrderInfo order = new OrderInfo(); order.OrderID = Guid.NewGuid(); order.OriginName = "起点" + ran.Next(1000000, 9999999).ToString(); order.TerminalName = "终点" + ran.Next(1000000, 9999999).ToString(); order.OriginPoint = new Point(); order.OriginPoint.type = "Point"; order.OriginPoint.coordinates = new List<double> { bn, en }; order.TerminalPoint = new Point(); order.TerminalPoint.type = "Point"; order.TerminalPoint.coordinates = new List<double> { tbn, ten }; order.ActiveTime = dtt; order.IsByFind = false; order.IsDelete = false; order.UserID = Guid.NewGuid(); order.CreateTime = DateTime.Now; order.UpdateTime = DateTime.Now; MongoHelper.InsertOne<OrderInfo>("T_OrderInfo", order); } System.Console.WriteLine("haol"); System.Console.Read(); } } public class OrderInfo { /// <summary> /// 订单id /// </summary> public System.Guid OrderID { get; set; } /// <summary> /// 起点名称 /// </summary> public string OriginName { get; set; } /// <summary> /// 起点坐标 /// </summary> public Point OriginPoint { get; set; } /// <summary> /// 终点名称 /// </summary> public string TerminalName { get; set; } /// <summary> /// 终点坐标 /// </summary> public Point TerminalPoint { get; set; } /// <summary> /// 预约时间 /// </summary> public DateTime ActiveTime { get; set; } /// <summary> /// 是否已被匹配 /// </summary> public bool IsByFind { get; set; } /// <summary> /// 是否已被删除 0未删除 1已删除 /// </summary> public bool IsDelete { get; set; } /// <summary> /// 用户ID /// </summary> public System.Guid UserID { get; set; } /// <summary> /// 创建时间 /// </summary> public System.DateTime CreateTime { get; set; } /// <summary> /// 最后修改时间 /// </summary> public System.DateTime UpdateTime { get; set; } } public class Point { public string type { get; set; } public List<double> coordinates { get; set; } } }
获取大于时间的数据
db.getCollection('T_OrderInfo').find({"ActiveTime":{"$gt":new Date("2016-07-07")}});
查询匹配起点,终点,Mongodb不能一次查询匹配两个坐标,只能分别查询,然后再进行匹配筛选
using System; using System.Collections.Generic; using System.Linq; using System.Web; using CompanyName.DepartmentName.Models; using CompanyName.DepartmentName.Common.Util; using MongoDB; using MongoDB.Linq; using MongoDB.GridFS; namespace CompanyName.DepartmentName.Functions { public class PollMongodbData { DBEntities entity = new DBEntities(); public void Poll() { int PageSize = 2000; int CurrentPage = 1; //范围 int Range = 2000;//单位米 List<OrderInfo> result = new List<OrderInfo>(); MongoDBHelper<OrderInfo> helper = new MongoDBHelper<OrderInfo>("T_OrderInfo"); var doc = new Document(); doc.Add("ActiveTime", new Document("$gt", DateTime.Now)); doc.Add("IsDelete", false); var sort = new Document(); sort.Add("CreateTime", 1); bool IsBreak = false; while (!IsBreak) { List<OrderInfo> DataList = MongoHelper.GetList<OrderInfo>("T_OrderInfo", doc, sort, CurrentPage, PageSize); foreach (var data in DataList) { if (data.OrderID == Guid.Empty) { break; } //防止匹配以后再次匹配 if(result.Select(x => x.OrderID).Contains(data.OrderID)) { continue; } //var ActiveTimeDC = new Document(); var OriginPointDC = new Document(); var TerminalPointDC = new Document(); //起点匹配 OriginPointDC.Add("ActiveTime", new Document("$gt", data.ActiveTime.AddMinutes(-30)).Add("$lt", data.ActiveTime.AddMinutes(30))); OriginPointDC.Add("IsDelete", false); OriginPointDC.Add("OrderID", new Document("$ne", data.OrderID)); OriginPointDC.Add("OriginPoint", new Document("$near", new Document("$geometry", new Document("type", "Point").Add("coordinates", data.OriginPoint.coordinates)).Add("$maxDistance", Range))); //终点匹配(因为mongodb不能一次匹配两个地理位置,只能一个个匹配,匹配终点,起点,再进一步进行筛选) TerminalPointDC.Add("ActiveTime", new Document("$gt", data.ActiveTime.AddMinutes(-30)).Add("$lt", data.ActiveTime.AddMinutes(30))); TerminalPointDC.Add("IsDelete", false); TerminalPointDC.Add("OrderID", new Document("$ne", data.OrderID)); TerminalPointDC.Add("TerminalPoint", new Document("$near", new Document("$geometry", new Document("type", "Point").Add("coordinates", data.TerminalPoint.coordinates)).Add("$maxDistance", Range))); List<OrderInfo> ReturnList = MongoHelper.GetList<OrderInfo>("T_OrderInfo", OriginPointDC, 1, 100000000); List<OrderInfo> ReturnList2 = MongoHelper.GetList<OrderInfo>("T_OrderInfo", OriginPointDC, 1, 100000000); var isT = false; foreach (var r in ReturnList) { foreach (var r2 in ReturnList2) { //必须判断result是否已经存在该数据 if (r.OrderID == r2.OrderID&&!result.Select(x=>x.OrderID).Contains(r.OrderID)) { data.BatchID = Guid.NewGuid(); r.BatchID = data.BatchID; result.Add(data); result.Add(r); isT = true; break; } } if (isT) break; } } CurrentPage++; if (DataList.Count() < PageSize) { IsBreak = true; } } foreach (var r in result) { r.IsDelete = true; //删除已匹配数据 helper.Update(r, x => x.OrderID == r.OrderID); T_OrderInfo order = new T_OrderInfo(); order.CreateTime = r.CreateTime; order.OrderID = r.OrderID; order.OriginName = r.OriginName; order.OriginPoint = String.Join(",", r.OriginPoint.coordinates); order.IsDelete = false; order.TerminalName = r.TerminalName; order.TerminalPoint = string.Join(",", r.TerminalPoint.coordinates); order.UpdateTime = r.UpdateTime; order.UserID = r.UserID; order.ActiveTime = r.ActiveTime; order.BatchID = r.BatchID; entity.T_OrderInfo.Add(order); } entity.SaveChanges(); } } }
==========================
Mongodb中查询Guid数据
Net中Guid传到Mongodb中变成LUUID
js查询1:
function LUUID(uuid) { var hex = uuid.replace(/[{}-]/g, ""); // removes extra characters return new UUID(hex); //creates new UUID } db.getCollection('T_OrderInfo').find({'UserID':LUUID("88460e2a-5eba-454e-b690-9ceb6aa35256")})
查询2:
db.getCollection('T_OrderInfo').find({'UserID':new UUID("88460e2a5eba454eb6909ceb6aa35256")})
http://www.cnblogs.com/huangxincheng/category/355399.html
http://www.cnblogs.com/ninestates/p/4738328.html
http://www.oschina.net/code/snippet_1387007_46081
http://chenzhou123520.iteye.com/blog/1637629