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().Limit().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().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 - ) * 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 - ) * 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 :/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().Limit().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", /111.12)));
var infoList2 = MongoHelper.GetList<OrderInfo>("T_OrderInfo", doc);
这样可以查询相近的地理位置
组合索引:
db.T_OrderInfo.ensureIndex( {ActiveTime:-, 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 = ; i < ; i++)
{
//起点坐标
var bn = Convert.ToDouble(bnn.ToString() + ran.Next(, ).ToString());
var en = Convert.ToDouble(enn.ToString() + ran.Next(, ).ToString());
//终点坐标
var tbn = Convert.ToDouble(tbnn.ToString() + ran.Next(, ).ToString());
var ten = Convert.ToDouble(tenn.ToString() + ran.Next(, ).ToString());
//时间
var dtt = dt.AddMinutes(ran.Next(-, ));
//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(, ).ToString();
order.TerminalName = "终点" + ran.Next(, ).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 = ;
int CurrentPage = ;
//范围
int Range = ;//单位米
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", );
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(-)).Add("$lt", data.ActiveTime.AddMinutes()));
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(-)).Add("$lt", data.ActiveTime.AddMinutes()));
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, , );
List<OrderInfo> ReturnList2 = MongoHelper.GetList<OrderInfo>("T_OrderInfo", OriginPointDC, , );
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
MongoDB的C#封装类的更多相关文章
- 【MongoDB】 基于C#官方驱动2.2版的封装类
一.前言 最近项目中要用到MongoDB,因此实现做了不少的调研.发现网上很多现有关于MongoDB C#官方驱动的调用方法都是基于1.8版本的,已经不是用了最新的2.2版本.因此我在基于C#官方驱动 ...
- Mongodb PHP封装类
分享一个Mongodb PHP封装类 <?php /** * Mongodb 基本操作API,支持基本类似关系统型数据库的操作接口 * * @version 1.0 * [说明] * * 1:该 ...
- 分享一个Mongodb PHP封装类
<?php /** * Mongodb 基本操作API,支持基本类似关系统型数据库的操作接口 * * @version 1.0 * [说明] * * 1:该版本API实现了 Mongodb 中最 ...
- Mongodb Manual阅读笔记:CH4 管理
4 管理 Mongodb Manual阅读笔记:CH2 Mongodb CRUD 操作Mongodb Manual阅读笔记:CH3 数据模型(Data Models)Mongodb Manual阅读笔 ...
- mongodb 操作类
在使用这个类之前,建议先自己去写,把方法都了解了再用,这样你就可以在适当的时候修个此类,另外请自己构建PagerInfo using System; using System.Collections. ...
- mongoDB操作命令及mongoDB的helper
此项目已开源,开源地址是: http://mongodbhelper-csharp.googlecode.com/svn/trunk/ mongodb的helper using System; usi ...
- spring集成mongodb封装的简单的CRUD
1.什么是mongodb MongoDB是一个基于分布式文件存储的数据库.由C++语言编写.旨在为WEB应用提供可扩展的高性能数据存储解决方案. mongoDB MongoDB是一个介 ...
- MongoDB学习笔记(五) MongoDB文件存取操作
由于MongoDB的文档结构为BJSON格式(BJSON全称:Binary JSON),而BJSON格式本身就支持保存二进制格式的数据,因此可以把文件的二进制格式的数据直接保存到MongoDB的文档结 ...
- 在.net下打造mongoDb基于官方驱动最新版本
还是一如既往先把结构图放出来,上上个版本添加了redis的缓存,但是不满足我的需求,因为公司有项目要求是分布式所以呢,这里我就增加了mongoDb进行缓存分布式,好了先看结构图. 总的来说比较蛋疼,因 ...
随机推荐
- Leetcode | Parentheses 相关
Generate Parentheses Given n pairs of parentheses, write a function to generate all combinations of ...
- Unattend.xml应答文件制作(WISM)-- 转自爱做梦的鱼
将制作好的应答文件unattend.xml拷贝到模板机sysprep目录下,然后在cmd下运行(unattend.xml文件可自定义名称) sysprep /generalize /oobe /s ...
- 【应用笔记】【AN001】VC#开发环境下基于以太网的4-20mA电流采集(基于modbus tcp 协议)
版本:第一版 作者:毛鹏 杨帅 日期:20151108 简介 4-20mA电流环具有广泛的应用前景,在许多行业中都发挥着重要作用.本文主要介绍了以太网接口的4-20mA电流采集模块在VC#环境下进行温 ...
- 利用poi开源jar包操作Excel时删除行内容与直接删除行的区别
一般情况下,删除行时会面临两种情况:删除行内容但保留行位置.整行删除(删除后下方单元格上移).对应的删除方法分别是: void removeRow(Row row)//Remove a row fro ...
- 《Java核心技术卷二》笔记(二)文件操作和内存映射文件
文件操作 上一篇已经总结了流操作,其中也包括文件的读写.文件系统除了读写以为还有很多其他的操作,如复制.移动.删除.目录浏览.属性读写等.在Java7之前,一直使用File类用于文件的操作.Java7 ...
- Radeon HD 7850 vs Radeon R9 270X
Radeon HD 7850 vs Radeon R9 270X HW compare Intro The Radeon HD 7850 comes with a GPU core speed ...
- Centos下使用Heartbeat实现集群[转]
Linux 包括 CentOS 下高可用性(HA:High Availability)集群方案很多,而 Heartbeat 是比较常见和性价比比较高的一种。一、硬件及网络连接 群集一般需要2台以上服务 ...
- Linux+postfix+extmail+dovecot打造基于web页面的邮件系统
原文地址:http://blog.csdn.net/deansrk/article/details/6717720 最终效果图: 准备阶段:需要手动下载的软件包: postfix-2.6.5.tar. ...
- [收藏]NET技术+25台服务器怎样支撑世界第54大网站
.NET技术+25台服务器怎样支撑世界第54大网站 英文原文:StackOverflow Update: 560M Pageviews A Month, 25 Servers, And It's ...
- ::after,::before使用
::after,::before使用 1.:before 选择器在被选元素的内容前面插入内容. 请使用 content 属性来指定要插入的内容. <!DOCTYPE html> < ...