MongoDB的C#封装类

时间:2022-09-05 13:50:50

代码:

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" } )

MongoDB的C#封装类

查找距离为附近为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&num;官方驱动2&period;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学习笔记&lpar;五&rpar; MongoDB文件存取操作

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

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

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

随机推荐

  1. mysql 修改密码

    安装完成后,默认本地登录超级管理员root,密码为空连接服务后(先停止服务,在wamp中运行mysql控制台enterpass:直接回车),执行set password for root@localh ...

  2. linux驱动中printk的使用注意事项

    今天在按键驱动中增加printk(KERN_INFO "gpio_keys_gpio_isr()\n");在驱动加载阶段可以输出调试信息,但驱动加载起来后的信息,在串口端看不到输出 ...

  3. UITapGestureRecognizer

    UITapGestureRecognizer IOS的手势非常多, 但是特别容易其他视图起冲突的手势,要数UITapGestureRecognizer 于是有了gestureRecognizerSho ...

  4. &lbrack;Ubuntu&rsqb; Ubuntu14&period;04 64bit 编译安装nginx1&period;7&plus;php5&period;4&plus;mysql5&period;6

    我的操作系统是Ubuntu14.04,其它linux系统的操作流程类似. 主要安装的软件是nginx1.7+php5.4+mysql5.6 1. 创建必要目录 sudo mkdir ~/setup s ...

  5. MyEclipse-File Serarch时报错:Problems encountered during text search

  6. C&plus;&plus;学习笔记之作用域为类的常量和作用域内的枚举

    一.作用域为类的常量 有些情况下,使符号常量的作用域为类很有用.如,类声明(不是定义)可能使用字面值30来指定数组长度,由于该常量对于所有对象来说都是相同的,因此创建一个由所有对象共享的常量是个不错的 ...

  7. &lbrack;LOJ 1248&rsqb; Dice &lpar;III&rpar;

    G - Dice (III) Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%lld & %llu Descri ...

  8. mysql sql 基础总结

    1 mysql top n使用 select * from table limit n; 2    统配符使用必须和like结合使用 like % 通配符 描述 % 替代一个或多个字符 _ 仅替代一个 ...

  9. Django—视图

    索引 一.URLconf 二.视图 三.HttpReqeust对象 3.1 QueryDict对象 3.2 GET和POST属性 四.HttpResponse对象 4.1 子类JsonResponse ...

  10. docker环境搭建

    参考地址:https://www.imooc.com/article/details/id/25228 操作系统Centos7 1.替换yum源为阿里云yum源: //备份yum源 mv /etc/y ...