以下是本人学习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. 流畅web动画的十个法则

    from me: web动画能够带来一个非常酷炫的效果,能够让页面有一个更好的用户体验.对于良好的动画性能没有高招,除了将大量的时间放在测试和优化,当然最重要的还是要易于维护. 流畅web动画的十大法 ...

  2. 跟着百度学PHP[4]OOP面对对象编程-6-构造方法(__construct)和构析方法(__destruct)

    函数就是成员方法(方法有三:构造方法.成员方法.析构方法) 下面是两种方法. 构造方法和构析方法 00x1 构造方法 构造方法会在创建对象之后自动调用.其名称为__construct <?php ...

  3. Android 异步消息处理机制解析

    Android 中的异步消息处理主要由四个部分组成,Message.Handler.MessageQueue.Looper.下面将会对这四个部分进行一下简要的介绍. 1. Message: Messa ...

  4. CCF 模拟B 无脑循环+输入输出外挂

    http://115.28.138.223:81/view.page?opid=2#code 代码一有WA点80分 #include<iostream> #include<cstdi ...

  5. python入门教程链接

    python安装 选择 2.7及以上版本 linux: 一般都自带 windows: https://www.python.org/downloads/windows/ mac os: https:/ ...

  6. @PathVariable注解

    spring mvc中的@PathVariable是用来获得请求url中的动态参数的,十分方便,复习下: . @Controller public class TestController { @Re ...

  7. 在Webstorm/Phpstorm中设置连接FTP,并快速进行文件比较,上传下载,同步等操作

    Phpstorm除了能直接打开localhost文件之外,还可以连接FTP,除了完成正常的数据传递任务之外,还可以进行本地文件与服务端文件的异同比较,同一文件自动匹配目录上传,下载,这些功能是平常ID ...

  8. .net MVC借助Iframe实现无刷新上传文件

    html: <div id="uploadwindow" style="display: none;"> <form action=" ...

  9. 字符串、字符、字节以及bit位小结与疑问

    字符串是由一个个字符组成的,每个字符又有一个或多个字节来表示,每个字节又由8个bit位来表示 在C#里 字符串通常由string来声明,字符由char来声明,字节由byte来表示,位由bit来表示,具 ...

  10. C++复制控制

    1.复制构造函数可用于: (1)根据另一个同类型的对象显示或隐式初始化一个对象 string str1="test";   //隐式 string str2=str1; //显示 ...