MangoDB的C#Driver驱动简单例子
以下是本人学习C#Driver驱动简单的学习例子。GridFS的增删查操作 和 表的增删查改操作。


public class MongoServerHelper
{
public static string dataBase = "File";
public static string fsName = "fs"; private static string _IP = "192.168.1.60";
private static int _port = ; public MongoServer GetMongoServer()
{
MongoServerSettings Settings = new MongoServerSettings();
Settings.Server = new MongoServerAddress(_IP, _port);
//最大连接池
Settings.MaxConnectionPoolSize = ;
//最大闲置时间
Settings.MaxConnectionIdleTime = TimeSpan.FromSeconds();
//链接时间
Settings.ConnectTimeout = TimeSpan.FromSeconds();
//等待队列大小
Settings.WaitQueueSize = ;
//socket超时时间
Settings.SocketTimeout = TimeSpan.FromSeconds();
//队列等待时间
Settings.WaitQueueTimeout = TimeSpan.FromSeconds();
//操作时间
Settings.OperationTimeout = TimeSpan.FromSeconds();
MongoServer server = new MongoServer(Settings);
return server;
}
}
public class BaseDAL
{
public MongoServerHelper mongoServerHelper = new MongoServerHelper();
private MongoServer server = null; public BaseDAL()
{
server = mongoServerHelper.GetMongoServer();
} /// <summary>
/// 新增
/// </summary>
public Boolean Insert(String collectionName, BsonDocument document)
{
server.Connect();
MongoDatabase database = server.GetDatabase(MongoServerHelper.dataBase);
MongoCollection<BsonDocument> collection = database.GetCollection<BsonDocument>(collectionName);
try
{
collection.Insert(document);
server.Disconnect();
return true;
}
catch
{
server.Disconnect();
return false;
}
} /// <summary>
/// 新增
/// </summary>
public Boolean Insert<T>(String collectionName, T t)
{
server.Connect();
MongoDatabase database = server.GetDatabase(MongoServerHelper.dataBase);
var collection = database.GetCollection<T>(collectionName);
try
{
collection.Insert(t);
server.Disconnect();
return true;
}
catch
{
server.Disconnect();
return false;
}
} /// <summary>
/// 批量新增
/// </summary>
public IEnumerable<WriteConcernResult> Insert<T>(String collectionName, List<T> list)
{
server.Connect();
MongoDatabase database = server.GetDatabase(MongoServerHelper.dataBase);
var collection = database.GetCollection<T>(collectionName);
try
{
IEnumerable<WriteConcernResult> result = collection.InsertBatch(list);
server.Disconnect();
return result;
}
catch
{
server.Disconnect();
return null;
}
} /// <summary>
/// 修改
/// </summary>
public WriteConcernResult Update(String collectionName, IMongoQuery query, QueryDocument update)
{
server.Connect();
MongoDatabase database = server.GetDatabase(MongoServerHelper.dataBase);
MongoCollection<BsonDocument> collection = database.GetCollection<BsonDocument>(collectionName);
try
{
var new_doc = new UpdateDocument() { { "$set", update } };
//UpdateFlags设置为Multi时,可批量修改
var result = collection.Update(query, new_doc, UpdateFlags.Multi);
server.Disconnect();
return result;
}
catch
{
return null;
}
} /// <summary>
/// 移除匹配的集合
/// </summary>
public Boolean Remove(String collectionName, IMongoQuery query)
{
server.Connect();
MongoDatabase database = server.GetDatabase(MongoServerHelper.dataBase);
MongoCollection<BsonDocument> collection = database.GetCollection<BsonDocument>(collectionName);
try
{
collection.Remove(query);
server.Disconnect();
return true;
}
catch
{
server.Disconnect();
return false;
}
} /// <summary>
/// 分页查询
/// </summary>
public List<T> GetPageList<T>(String collectionName, IMongoQuery query, string sort, bool isDesc, int index, int pageSize, out long rows)
{
server.Connect();
MongoDatabase database = server.GetDatabase(MongoServerHelper.dataBase);
MongoCollection<BsonDocument> collection = database.GetCollection<BsonDocument>(collectionName);
List<T> list;
try
{
rows = collection.FindAs<T>(query).Count();
if (isDesc)
{
list = collection.FindAs<T>(query).SetSortOrder(SortBy.Descending(sort)).SetSkip(index).SetLimit(pageSize).ToList();
}
else
{
list = collection.FindAs<T>(query).SetSortOrder(SortBy.Ascending(sort)).SetSkip(index).SetLimit(pageSize).ToList();
}
server.Disconnect();
return list; }
catch
{
rows = ;
server.Disconnect();
return null;
}
} /// <summary>
/// 查询对象集合
/// </summary>
public List<T> GetList<T>(String collectionName, IMongoQuery query, string[] sort, bool isDesc)
{
server.Connect();
MongoDatabase database = server.GetDatabase(MongoServerHelper.dataBase);
MongoCollection<BsonDocument> collection = database.GetCollection<BsonDocument>(collectionName);
List<T> list;
try
{
if (isDesc)
{
list= collection.FindAs<T>(query).SetSortOrder(SortBy.Descending(sort)).ToList();
server.Disconnect();
return list;
}
else
{
list =collection.FindAs<T>(query).SetSortOrder(SortBy.Ascending(sort)).ToList();
server.Disconnect();
return list;
}
}
catch
{
return null;
}
} /// <summary>
/// 总数
/// </summary>
public long Count(string collectionName, IMongoQuery query)
{
server.Connect();
MongoDatabase database = server.GetDatabase(MongoServerHelper.dataBase);
MongoCollection<BsonDocument> collection = database.GetCollection<BsonDocument>(collectionName);
try
{
server.Disconnect();
return collection.Count(query);
}
catch
{
server.Disconnect();
return ;
}
}
}
public class BaseEntity
{
/// <summary>
/// 基类对象的ID,MongoDB要求每个实体类必须有的主键
/// </summary>
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
}
public class User : BaseEntity
{
public string Name { get; set; }
public int No { get; set; }
public DateTime Time { get; set; }
public double Money { get; set; }
}
BsonDocument doc = new BsonDocument()
{
{"Name","Mongo"},
{"No",},
{"Time",DateTime.Now},
{"Money",102.123}
};
_daoMongo.Insert("MongoUser", doc); User model = new User() { Name = "MongoT", No = , Time = DateTime.Now, Money = 11.22 };
_daoMongo.Insert<User>("MongoUser", model);
List<User> List = new List<User>();
for (int i = ; i < ; i++)
{
List.Add(new User() { Name = "MongoT" + i, No = i, Time = DateTime.Now, Money = 11.22 });
}
_daoMongo.Insert<User>("MongoUser", List); QueryDocument update = new QueryDocument() { { "Name", "" }, { "Money", 1000.555 } };
_daoMongo.Update("MongoUser", Query<User>.EQ(m => m.No, ), update); _daoMongo.Remove("MongoUser", Query<User>.EQ(m => m.No, )); long aa = _daoMongo.Count("MongoUser", Query<User>.GT(m => m.No, )); List<User> list = _daoMongo.GetList<User>("MongoUser", Query<User>.GT(m => m.No, ), new string[] { "No" }, true);
List<User> list2 = _daoMongo.GetPageList<User>("MongoUser", Query<User>.GT(m => m.No, ), "No", true, , , out aa);
/// <summary>
/// GridFS文件处理
/// </summary>
public class GridFSHelper
{
private MongoServerHelper mongoServerHelper = new MongoServerHelper();
protected internal MongoServer server = null; public GridFSHelper()
{
server = mongoServerHelper.GetMongoServer();
} public string AddDoc(byte[] content, string ContentType, string fileName)
{
try
{
string fileID = Guid.NewGuid().ToString();
this.server.Connect();
MongoGridFSCreateOptions optioms = new MongoGridFSCreateOptions()
{
ChunkSize = ,
UploadDate = DateTime.Now.AddHours(),
ContentType = ContentType,
Id = fileID
};
MongoGridFS fs = new MongoGridFS(this.server, MongoServerHelper.dataBase, new MongoGridFSSettings() { Root = MongoServerHelper.fsName }); using (MongoGridFSStream gfs = fs.Create(fileName, optioms))
{
gfs.Write(content, , content.Length);
}
return fileID;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (this.server != null)
this.server.Disconnect();
}
} public byte[] GetDoc(string fileID)
{
try
{
this.server.Connect();
MongoDatabase db = this.server.GetDatabase(MongoServerHelper.dataBase);
MongoGridFS fs = new MongoGridFS(this.server, MongoServerHelper.dataBase, new MongoGridFSSettings() { Root = MongoServerHelper.fsName });
byte[] bytes = null;
MongoGridFSFileInfo info = fs.FindOneById(fileID);
using (MongoGridFSStream gfs = info.Open(FileMode.Open))
{
bytes = new byte[gfs.Length];
gfs.Read(bytes, , bytes.Length);
}
return bytes;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (this.server != null)
this.server.Disconnect();
}
} public bool DeleteDoc(string fileID)
{
if (string.IsNullOrEmpty(fileID))
return false; try
{
this.server.Connect();
MongoDatabase db = this.server.GetDatabase(MongoServerHelper.dataBase);
MongoGridFS fs = new MongoGridFS(this.server, MongoServerHelper.dataBase, new MongoGridFSSettings() { Root = MongoServerHelper.fsName });
fs.DeleteById(fileID);
return true;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (this.server != null)
this.server.Disconnect();
}
}
}
public ActionResult Load()
{
HttpPostedFileBase hpf = Request.Files["fileUpload"];
string objectID;
objectID = _gridFSHelper.AddDoc(StreamToBytes(hpf.InputStream), hpf.ContentType, hpf.FileName);
return Content(objectID);
}



MangoDB的C#Driver驱动简单例子的更多相关文章
- RabbitMQ驱动简单例子
using RabbitMQ.Client; using RabbitMQ.Client.Events; using System; using System.Collections.Generic; ...
- NHibernate的简单例子
NHibernate的简单例子 @(编程) [TOC] 因为项目需求,搭了一个NHibernate的例子,中间遇到了一些问题,通过各种方法解决了,在这里记录一下最后的结果. 1. 需要的dll Com ...
- Hibernate4.2.4入门(一)——环境搭建和简单例子
一.前言 发下牢骚,这段时间要做项目,又要学框架,搞得都没时间写笔记,但是觉得这知识学过还是要记录下.进入主题了 1.1.Hibernate简介 什么是Hibernate?Hibernate有什么用? ...
- 一个简单例子:贫血模型or领域模型
转:一个简单例子:贫血模型or领域模型 贫血模型 我们首先用贫血模型来实现.所谓贫血模型就是模型对象之间存在完整的关联(可能存在多余的关联),但是对象除了get和set方外外几乎就没有其它的方法,整个 ...
- AgileEAS.NET SOA 中间件平台.Net Socket通信框架-简单例子-实现简单的服务端客户端消息应答
一.AgileEAS.NET SOA中间件Socket/Tcp框架介绍 在文章AgileEAS.NET SOA 中间件平台Socket/Tcp通信框架介绍一文之中我们对AgileEAS.NET SOA ...
- spring mvc(注解)上传文件的简单例子
spring mvc(注解)上传文件的简单例子,这有几个需要注意的地方1.form的enctype=”multipart/form-data” 这个是上传文件必须的2.applicationConte ...
- ko 简单例子
Knockout是在下面三个核心功能是建立起来的: 监控属性(Observables)和依赖跟踪(Dependency tracking) 声明式绑定(Declarative bindings) 模板 ...
- mysql定时任务简单例子
mysql定时任务简单例子 ? 1 2 3 4 5 6 7 8 9 如果要每30秒执行以下语句: [sql] update userinfo set endtime = now() WHE ...
- java socket编程开发简单例子 与 nio非阻塞通道
基本socket编程 1.以下只是简单例子,没有用多线程处理,只能一发一收(由于scan.nextLine()线程会进入等待状态),使用时可以根据具体项目功能进行优化处理 2.以下代码使用了1.8新特 ...
随机推荐
- ExtJs xtype类型介绍
自定义组件在定义的时候可以通过xtype配置为组件指定xtype短名称,此后创建对象可以通过xtype来创建自定义对象了,示例代码如下: Ext.define('MyApp.PressMeButton ...
- am335x sd卡启动开启识别emmc kernel 上的改动
sbc 7109-454 sd 卡启动qt系统后一直识别不了 emmc 也就是mmc1口, 一开始以为是硬件初始化的问题,后面又以为是io口复用,最后才知道是根本没有注册mmc1设备. 更改下面的代 ...
- 绝对实用 NAT + VLAN +ACL管理企业网络
在企业中,要实现所有的员工都能与互联网进行通信,每个人各使用一个公网地址是很不现实的.一般,企业有1个或几个公网地址,而企业有几十.几百个员工.要想让所有的员工使用这仅有的几个公网地址与互联网通信该怎 ...
- How can I determine the URL that a local Git repository was originally cloned from?
git remote show origin from: http://stackoverflow.com/questions/4089430/how-can-i-determine-the-url- ...
- neutron 网络配置flat模式
使用flat模式,直接使用物理网络的子网,配置如下:
- 【leetcode】Word Search
Word Search Given a 2D board and a word, find if the word exists in the grid. The word can be constr ...
- POJ 1002
#include <stdio.h> #include <string.h> #include <stdlib.h> struct In{ int a; ]; }p ...
- Debian上安装Apache+Django全过程
-->start sudo apt-get install apache2 libapache2-mod-wsgi #https://wiki.debian.org/zh_CN/Apache s ...
- 如何恢复低版本的FlashPlayer
本人做页游开发时,游戏用户那边经常会遇到一些很奇怪的问题.比如: 1.用户进入游戏,只显示游戏部分界面,chrome浏览器是正常的,就IE死活不行. 2.进入游戏时白屏或者一直加载不上. 3.玩游戏时 ...
- (转载)linux中设备文件配置程序udev详解
如果你使用Linux比较长时间了,那你就知道,在对待设备文件这块,Linux改变了几次策略.在Linux早期,设备文件仅仅是是一些带有适当的属性集的普通文件,它由mknod命令创建,文件存放在/dev ...