以下是本人学习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学习笔记(十六)——数据库操作(上)

    //此系列博文是<第一行Android代码>的学习笔记,如有错漏,欢迎指正! Android 为了让我们能够更加方便地管理数据库,专门提供了一个 SQLiteOpenHelper帮助类, ...

  2. 编写Delphi控件属性Stored和Default的理解及应用

    property ButtonSize: Integer read FButtonSize write SetButtonSize default 0;    property Color: TCol ...

  3. zabbix之php安装

    转载自: http://www.ttlsa.com/nginx/nginx-php-5_5/ php下载 https://pan.baidu.com/s/1qYGo8bE

  4. 解决maven项目移动

    解决使用maven的工程移动到另一台电脑(电脑无法访问maven中央仓库问题) 移动后出现下述结果: Publishing failedPublishing failed with multiple ...

  5. supervisor的配置

    看了下文档,比较多.http://www.supervisord.org/ 抱着试试又不会怀孕的心态,trying,碰了几鼻子灰,记录如下, 方便大家 1. 安装 easy_install super ...

  6. Portal

    https://chenliang0571.wordpress.com/2013/12/08/openwrt-wifidog-wifi-hotspots/http://www.h3c.com.cn/M ...

  7. Unity3d 鼠标拣选小功能集合

    最近在做一些优化工具,把鼠标拣选的功能单独抽出来. 可遍历所有选中的某类型资源,会递归文件夹 可编译所有prefab的某个Component,也是递归的 using UnityEngine; usin ...

  8. ios 使用xib时,在UIScrollView中添建内容view时,使用约束的注意

    请参与一下链接:http://segmentfault.com/a/1190000002462033 简单的说下,就是必须写满一个view的6个约束,就是上下左右高宽,让scrollview 能够根据 ...

  9. Effective C++ -----条款41:了解隐式接口和编译期多态

    classes和templates都支持接口(interface)和多态(polymorphism). 对classes而言接口是显式的(explicit),以函数签名为中心.多态则是通过virtua ...

  10. yii 多模板

    main.php: //替换所有模板 //加载文件名为first的模板 //       'theme'=>'theme1', 'components'=>array(           ...