代码:

samus驱动

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#封装类的更多相关文章

  1. 【MongoDB】 基于C#官方驱动2.2版的封装类

    一.前言 最近项目中要用到MongoDB,因此实现做了不少的调研.发现网上很多现有关于MongoDB C#官方驱动的调用方法都是基于1.8版本的,已经不是用了最新的2.2版本.因此我在基于C#官方驱动 ...

  2. Mongodb PHP封装类

    分享一个Mongodb PHP封装类 <?php /** * Mongodb 基本操作API,支持基本类似关系统型数据库的操作接口 * * @version 1.0 * [说明] * * 1:该 ...

  3. 分享一个Mongodb PHP封装类

    <?php /** * Mongodb 基本操作API,支持基本类似关系统型数据库的操作接口 * * @version 1.0 * [说明] * * 1:该版本API实现了 Mongodb 中最 ...

  4. Mongodb Manual阅读笔记:CH4 管理

    4 管理 Mongodb Manual阅读笔记:CH2 Mongodb CRUD 操作Mongodb Manual阅读笔记:CH3 数据模型(Data Models)Mongodb Manual阅读笔 ...

  5. mongodb 操作类

    在使用这个类之前,建议先自己去写,把方法都了解了再用,这样你就可以在适当的时候修个此类,另外请自己构建PagerInfo using System; using System.Collections. ...

  6. mongoDB操作命令及mongoDB的helper

    此项目已开源,开源地址是: http://mongodbhelper-csharp.googlecode.com/svn/trunk/ mongodb的helper using System; usi ...

  7. spring集成mongodb封装的简单的CRUD

    1.什么是mongodb         MongoDB是一个基于分布式文件存储的数据库.由C++语言编写.旨在为WEB应用提供可扩展的高性能数据存储解决方案. mongoDB MongoDB是一个介 ...

  8. MongoDB学习笔记(五) MongoDB文件存取操作

    由于MongoDB的文档结构为BJSON格式(BJSON全称:Binary JSON),而BJSON格式本身就支持保存二进制格式的数据,因此可以把文件的二进制格式的数据直接保存到MongoDB的文档结 ...

  9. 在.net下打造mongoDb基于官方驱动最新版本

    还是一如既往先把结构图放出来,上上个版本添加了redis的缓存,但是不满足我的需求,因为公司有项目要求是分布式所以呢,这里我就增加了mongoDb进行缓存分布式,好了先看结构图. 总的来说比较蛋疼,因 ...

随机推荐

  1. [转]用Linq取CheckBoxList選取項目的值

    本文转自:http://www.dotblogs.com.tw/hatelove/archive/2011/11/17/linq-checkboxlist-items-selected-values. ...

  2. Leetcode | substr()

    求子串当然最经典的就是KMP算法了.brute force算法在leetcode上貌似也有一些技巧. brute force: char* StrStr(const char *str, const ...

  3. Spring框架中的定时器 如何使用和配置

    目标类 <bean id="myTimer" class="com.timer.MyTimer"></bean> 配置你的定时器详情 & ...

  4. LightOJ 1188 Fast Queries(简单莫队)

    1188 - Fast Queries    PDF (English) Statistics Forum Time Limit: 3 second(s) Memory Limit: 64 MB Gi ...

  5. Apache POI使用详解

    Apache POI使用详解 1.POI结构与常用类 (1)POI介绍 Apache POI是Apache软件基金会的开源项目,POI提供API给Java程序对Microsoft Office格式档案 ...

  6. redmine问题

    问题1: 404 版本库中不存在该条目和(或)其修订版本. 1.1 GIT库: 参考:http://stackoverflow.com/questions/13000247/redmine-gitol ...

  7. OpenGL EXT: shader_buffer_load

    http://www.opengl.org/registry/specs/NV/shader_buffer_load.txt Overview At a very coarse level, GL h ...

  8. 达内培训:php在线端口扫描器

    达内培训:php在线端口扫描器 [来源] 达内    [编辑] 达内   [时间]2012-12-21 这个扫描器很简单.就是用了一个数组来定义端口的相关信息,原理就是用fsockopen函数连接,如 ...

  9. JavaScript 数组详解(转)

    在程序语言中数组的重要性不言而喻,JavaScript中数组也是最常使用的对象之一,数组是值的有序集合,由于弱类型的原因,JavaScript中数组十分灵活.强大,不像是Java等强类型高级语言数组只 ...

  10. spotlight监控工具使用

    利用spotlight工具可以监控如下系统:        1.Spotlight on Unix 监控Linux服务器 1)安装 Spotlight on Unix 2)配置spotlight登陆用 ...