以下是本人学习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驱动简单例子的更多相关文章

  1. RabbitMQ驱动简单例子

    using RabbitMQ.Client; using RabbitMQ.Client.Events; using System; using System.Collections.Generic; ...

  2. NHibernate的简单例子

    NHibernate的简单例子 @(编程) [TOC] 因为项目需求,搭了一个NHibernate的例子,中间遇到了一些问题,通过各种方法解决了,在这里记录一下最后的结果. 1. 需要的dll Com ...

  3. Hibernate4.2.4入门(一)——环境搭建和简单例子

    一.前言 发下牢骚,这段时间要做项目,又要学框架,搞得都没时间写笔记,但是觉得这知识学过还是要记录下.进入主题了 1.1.Hibernate简介 什么是Hibernate?Hibernate有什么用? ...

  4. 一个简单例子:贫血模型or领域模型

    转:一个简单例子:贫血模型or领域模型 贫血模型 我们首先用贫血模型来实现.所谓贫血模型就是模型对象之间存在完整的关联(可能存在多余的关联),但是对象除了get和set方外外几乎就没有其它的方法,整个 ...

  5. AgileEAS.NET SOA 中间件平台.Net Socket通信框架-简单例子-实现简单的服务端客户端消息应答

    一.AgileEAS.NET SOA中间件Socket/Tcp框架介绍 在文章AgileEAS.NET SOA 中间件平台Socket/Tcp通信框架介绍一文之中我们对AgileEAS.NET SOA ...

  6. spring mvc(注解)上传文件的简单例子

    spring mvc(注解)上传文件的简单例子,这有几个需要注意的地方1.form的enctype=”multipart/form-data” 这个是上传文件必须的2.applicationConte ...

  7. ko 简单例子

    Knockout是在下面三个核心功能是建立起来的: 监控属性(Observables)和依赖跟踪(Dependency tracking) 声明式绑定(Declarative bindings) 模板 ...

  8. mysql定时任务简单例子

    mysql定时任务简单例子 ? 1 2 3 4 5 6 7 8 9     如果要每30秒执行以下语句:   [sql] update userinfo set endtime = now() WHE ...

  9. java socket编程开发简单例子 与 nio非阻塞通道

    基本socket编程 1.以下只是简单例子,没有用多线程处理,只能一发一收(由于scan.nextLine()线程会进入等待状态),使用时可以根据具体项目功能进行优化处理 2.以下代码使用了1.8新特 ...

随机推荐

  1. Android 数据存储之 SQLite数据库存储

    ----------------------------------------SQLite数据库---------------------------------------------- SQLi ...

  2. BZOJ 2541: [Ctsc2000]冰原探险

    Descrption 有一些矩形障碍,碰到障碍会停下,求从一个点到另一个点的最少移动步数. Sol BFS. 因为题目的特殊性质,两个矩形没有任何相邻,起始点和终点和矩形没有相邻. 所以从一个点的移动 ...

  3. Android客户端的图形化拖放操作的设计实现

    为什么要拖放?拖放在某些UI交互中可以简化用户操作. 拖放的步骤包括哪些?“Drag and Drop”,拖放,顾名思义,总共就分三步:1, 开始拖起来:2, 正在拖:3, 放下,进行操作:在这三步里 ...

  4. Python自动化之线程进阶篇(二)

    queue队列 class queue.Queue(maxsize=0) #先入先出 class queue.LifoQueue(maxsize=0) #后入先出 class queue.Priori ...

  5. $_request,$post,$get的三者区别和特点

    一.$_request与$_post.$_get的区别和特点 $_REQUEST[]具用$_POST[] $_GET[]的功能,但是$_REQUEST[]比较慢.通过post和get方法提交的所有数据 ...

  6. 蓝牙模块连接后出现ANR,日志记录

    11-25 16:29:48.433 14507-14561/myapplication.com.myblue W/MALI: glDrawArrays:714: [MALI] glDrawArray ...

  7. rebot的使用

    rebot简要使用方法介绍 在介绍rebot前,首先说一下RobotFramework(后称RF)的主要输出文件.   当我们执行完一个RF脚本后,RF会输出3种文件.分别是Output.Log和Re ...

  8. Effective C++ -----条款35:考虑virtual函数以外的其他选择

    virtual函数的替代方案包括NVI手法及Strategy设计模式的多种手法.NVI手法自身是一个特殊形式的Template Method设计模式. 将机能从成员函数移到class外部函数,带来的一 ...

  9. 【leetcode】 Search a 2D Matrix (easy)

    Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the follo ...

  10. 【linux】linux下运行java程序

    参考了http://www.cnblogs.com/howard-queen/archive/2012/01/30/2331795.html 第一步:用vim先写一个java程序  first.jav ...