本篇是作为另一篇随笔的一部分‘搭建一个Web API项目

MogonDB官网:https://www.mongodb.org/

安装过程参考园友的分享http://www.cnblogs.com/lzrabbit/p/3682510.html

cmd client:

C:\Users\Administrator>D:
D:\> cd D:\MongoDB\Server\3.2\bin
D:\MongoDB\Server\3.2\bin>mongo 127.0.0.1:27017
>use zheyibu
>db.SEOStudent.find()

  

一、项目Frozen.MongoObjects

     /// <summary>
/// MongoDB支持的实体,必须要有Id
/// </summary>
public interface IEntity
{
[BsonId]
int Id { get; set; }
}
     /// <summary>
///
/// </summary>
public class SEOStudent : IEntity
{
/// <summary>
///
/// </summary>
public int Id { get; set; } public string Name { get; set; } }

二、项目Frozen.MongoCommon

(这部分的代码都是从园子里拷下来的,望大神们莫怪!本文不用于任何商业用途!)

IMongoDBRepositoryContextSettings

 using MongoDB.Driver;

 namespace Frozen.MongoCommon
{
/// <summary>
/// Represents that the implemented classes are MongoDB repository context settings.
/// </summary>
public interface IMongoDBRepositoryContextSettings
{
/// <summary>
/// Gets the database name.
/// </summary>
string DatabaseName { get; }
/// <summary>
/// Gets the instance of <see cref="MongoServerSettings"/> class which represents the
/// settings for MongoDB server.
/// </summary>
MongoClientSettings ClientSettings { get; }
/// <summary>
/// Gets the instance of <see cref="MongoDatabaseSettings"/> class which represents the
/// settings for MongoDB database.
/// </summary>
/// <param name="server">The MongoDB server instance.</param>
/// <returns>The instance of <see cref="MongoDatabaseSettings"/> class.</returns>
MongoDatabaseSettings GetDatabaseSettings(MongoClient client); }
}

MongoDBRepositoryContextSettings

 using MongoDB.Driver;
using System;
using System.Configuration; namespace Frozen.MongoCommon
{
/// <summary>
/// 表示基于MongoDB实现的仓储上下文的配置信息。
/// </summary>
/// <remarks>
/// 如果您的MongoDB配置不是默认的,您可以在此处修改MongoDB的配置信息,比如
/// 可以在ServerSettings里指定MongoDB的端口号等。
/// </remarks>
public class MongoDBRepositoryContextSettings : IMongoDBRepositoryContextSettings
{
private readonly string serverStr = "192.168.8.119";
private readonly int port = ;
private readonly string dbName = "zheyibu"; public MongoDBRepositoryContextSettings()
{
if(ConfigurationManager.AppSettings["MongoDBServer"]!=null)
{
serverStr = ConfigurationManager.AppSettings["MongoDBServer"];
}
if (ConfigurationManager.AppSettings["MongoDBServerPort"] != null)
{
port = Int32.Parse(ConfigurationManager.AppSettings["MongoDBServerPort"]);
}
if (ConfigurationManager.AppSettings["MongoDBDbName"] != null)
{
dbName = ConfigurationManager.AppSettings["MongoDBDbName"];
}
} #region IMongoDBRepositoryContextSettings Members
/// <summary>
/// 获取数据库名称。
/// </summary>
public string DatabaseName
{
get { return dbName; }
}
/// <summary>
/// 获取MongoDB的服务器配置信息。
/// </summary>
public MongoClientSettings ClientSettings
{
get
{
var settings = new MongoClientSettings();
settings.Server = new MongoServerAddress(serverStr, port);
settings.WriteConcern = WriteConcern.Acknowledged;
return settings;
}
}
/// <summary>
/// 获取数据库配置信息。
/// </summary>
/// <param name="server">需要配置的数据库实例。</param>
/// <returns>数据库配置信息。</returns>
public MongoDatabaseSettings GetDatabaseSettings(MongoClient client)
{
// 您无需做过多的更改:此处仅返回新建的MongoDatabaseSettings实例即可。
return new MongoDatabaseSettings();
} #endregion
}
}

IMongoDBRepositoryContext

 using Frozen.MongoObjects;
using MongoDB.Driver;
using System; namespace Frozen.MongoCommon
{
/// <summary>
/// Mongo DB Context
/// </summary>
public interface IMongoDBRepositoryContext
{
/// <summary>
/// Gets a <see cref="IMongoDBRepositoryContextSettings"/> instance which contains the settings
/// information used by current context.
/// </summary>
IMongoDBRepositoryContextSettings Settings { get; }
/// <summary>
/// Gets the <see cref="MongoCollection"/> instance by the given <see cref="Type"/>.
/// </summary>
/// <param name="type">The <see cref="Type"/> object.</param>
/// <returns>The <see cref="MongoCollection"/> instance.</returns>
IMongoCollection<T> GetCollection<T>() where T : IEntity; /// <summary>
/// 从MongoDB中清除所有类型为T的对象
/// </summary>
/// <typeparam name="T"></typeparam>
void ClearSequence<T>(); /// <summary>
/// 获取类型T的对象的下一个序列
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
int getNextSequence<T>();
}
}

MongoDBRepositoryContext

 using MongoDB.Bson.Serialization.Conventions;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using MongoDB.Driver.Linq;
using System.Threading;
using Frozen.MongoObjects; namespace Frozen.MongoCommon
{
/// <summary>
/// Represents the MongoDB repository context.
/// </summary>
public class MongoDBRepositoryContext : IMongoDBRepositoryContext
{
private readonly IMongoDBRepositoryContextSettings settings;
private readonly MongoClient client;
private readonly IMongoDatabase db; /// <summary>
/// 构造,初始化MongoClient
/// </summary>
/// <param name="settings"></param>
public MongoDBRepositoryContext(IMongoDBRepositoryContextSettings settings)
{
this.settings = settings;
client = new MongoClient(settings.ClientSettings);
db = client.GetDatabase(settings.DatabaseName);
} /// <summary>
/// Mongo 设置
/// </summary>
public IMongoDBRepositoryContextSettings Settings
{
get
{
return settings;
}
} /// <summary>
/// 获取一个集合
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public IMongoCollection<T> GetCollection<T>() where T : IEntity
{
return db.GetCollection<T>(typeof(T).Name);
} /// <summary>
/// 获取Id
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns>序列ID</returns>
public int getNextSequence<T>()
{
//此处代码需要优化,应该一个API方法就可以搞定
var collection = db.GetCollection<Counter>("counter"); string name = typeof(T).Name;
var filter = Builders<Counter>.Filter.Where(t => t.id == name);
var last = collection.Find(filter).FirstOrDefaultAsync().Result;
if (last == null)
{
collection.InsertOneAsync(new Counter() { id = name, seq = });
} var def = Builders<Counter>.Update.Inc(t => t.seq, );
collection.FindOneAndUpdateAsync(filter, def).Wait();
return collection.Find(filter).FirstOrDefaultAsync().Result.seq; } /// <summary>
/// 清除序列
/// </summary>
/// <typeparam name="T"></typeparam>
public void ClearSequence<T>()
{
var collection = db.GetCollection<Counter>("counter"); string name = typeof(T).Name;
var filter = Builders<Counter>.Filter.Where(t => t.id == name);
var def = Builders<Counter>.Update.Set(t => t.seq, );
collection.FindOneAndUpdateAsync(filter,def).Wait();
}
} /// <summary>
/// 序列
/// </summary>
public class Counter
{
/// <summary>
/// 类型的Id
/// </summary>
public string id { get; set; } /// <summary>
/// 当前的序列
/// </summary>
public int seq { get; set; }
}
}

MongoDBRepository

 using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using MongoDB.Driver;
using Frozen.MongoObjects; namespace Frozen.MongoCommon
{
/// <summary>
/// Represents the MongoDB repository.
/// </summary>
/// <typeparam name="T">实现了IEntity的实体类</typeparam>
public class MongoDBRepository<T> where T : class, IEntity
{
#region Private Fields private readonly IMongoDBRepositoryContext mongoDBRepositoryContext;
private IMongoCollection<T> collection; #endregion /// <summary>
/// 构造
/// </summary>
/// <param name="context"></param>
public MongoDBRepository(IMongoDBRepositoryContext context)
{
mongoDBRepositoryContext = context;
collection = mongoDBRepositoryContext.GetCollection<T>();
} /// <summary>
/// MongoBD Context,一个集合
/// </summary>
protected IMongoCollection<T> DataContext
{
get { return collection ?? (collection = mongoDBRepositoryContext.GetCollection<T>()); }
} /// <summary>
/// 添加类型实例到Mongo
/// </summary>
/// <param name="entity"></param>
public void Add(T entity)
{
if (entity.Id == )
{
entity.Id = mongoDBRepositoryContext.getNextSequence<T>();
}
collection.InsertOneAsync(entity).Wait();
} /// <summary>
/// 添加集合到Mongo
/// </summary>
/// <param name="entities"></param>
public void AddAll(IEnumerable<T> entities)
{
foreach (var it in entities)
{
if (it.Id == )
{
it.Id = mongoDBRepositoryContext.getNextSequence<T>();
}
}
collection.InsertManyAsync(entities).Wait();
} /// <summary>
/// 更新实例
/// </summary>
/// <param name="entity"></param>
public void Update(T entity)
{
var filter = Builders<T>.Filter.Where(t => t.Id == entity.Id);
collection.ReplaceOneAsync(filter, entity).Wait();
} /// <summary>
/// 更新一组实例
/// </summary>
/// <param name="entities"></param>
public void Update(IEnumerable<T> entities)
{
foreach (var it in entities)
{
Update(it);
}
} /// <summary>
/// 更新或添加一组实例
/// </summary>
/// <param name="entities"></param>
public void UpdateOrAddAll(IEnumerable<T> entities)
{
var list2 = new List<T>(); //will be add
foreach (var i in entities)
{
if (GetById(i.Id) != null)
{
Update(i);
}
else
{
list2.Add(i);
}
}
if (list2.Count > )
{
AddAll(list2);
}
} /// <summary>
/// 删除实例
/// </summary>
/// <param name="entity"></param>
public void Delete(T entity)
{
var filter = Builders<T>.Filter.Where(t => t.Id == entity.Id);
collection.DeleteOneAsync(filter).Wait();
} /// <summary>
/// 按条件删除
/// </summary>
/// <param name="where"></param>
public void Delete(Expression<Func<T, bool>> where)
{
collection.DeleteOneAsync(where).Wait();
} /// <summary>
/// 删除一组实例
/// </summary>
/// <param name="entities"></param>
public void DeleteAll(IEnumerable<T> entities)
{
var filter = Builders<T>.Filter.Where(t => t.Id > );
collection.DeleteManyAsync(filter).Wait();
} /// <summary>
/// 按Id 范围删除
/// </summary>
/// <param name="MinId"></param>
/// <param name="MaxId"></param>
public void DeleteMany(int MinId, int MaxId)
{
var filter = Builders<T>.Filter.Where(t => t.Id >= MinId && t.Id <= MaxId);
collection.DeleteManyAsync(filter).Wait();
} /// <summary>
/// 清除所以
/// </summary>
public void Clear()
{
var filter = Builders<T>.Filter.Where(t => t.Id > );
collection.DeleteManyAsync(filter).Wait();
mongoDBRepositoryContext.ClearSequence<T>();
} /// <summary>
/// 按id查询
/// </summary>
/// <param name="Id"></param>
/// <returns></returns>
public T GetById(long Id)
{
return collection.Find(t => t.Id == Id).FirstOrDefaultAsync().Result;
} /// <summary>
/// 按id查询
/// </summary>
/// <param name="Id"></param>
/// <returns></returns>
public T GetById(string Id)
{
var entityId = ;
int.TryParse(Id, out entityId);
return collection.Find(t => t.Id == entityId).FirstOrDefaultAsync().Result;
} /// <summary>
/// 按条件查询
/// </summary>
/// <param name="where"></param>
/// <returns></returns>
public T Get(Expression<Func<T, bool>> where)
{
return collection.Find(where).FirstOrDefaultAsync().Result;
} /// <summary>
/// 获取所有
/// </summary>
/// <returns></returns>
public IEnumerable<T> GetAll()
{
return collection.Find(t => t.Id > ).ToListAsync().Result;
} /// <summary>
/// 按条件获取
/// </summary>
/// <param name="where"></param>
/// <returns></returns>
public IEnumerable<T> GetMany(Expression<Func<T, bool>> where)
{
return collection.Find(where).ToListAsync().Result;
} /// <summary>
/// 获取所有
/// </summary>
/// <returns></returns>
public IEnumerable<T> GetAllLazy()
{
return collection.Find(t => t.Id > ).ToListAsync().Result;
} }
}

三、项目Frozen.MongoRepositories

ISEOStudentMongoRepo

using Frozen.Common.Interface;
using Frozen.MongoObjects; namespace Frozen.MongoRepositories
{
public interface ISEOStudentMongoRepo : IRepository<SEOStudent>
{ }
}

SEOStudentMongoRepo

 using Frozen.MongoCommon;
using Frozen.MongoObjects; namespace Frozen.MongoRepositories.Implementation
{
public class SEOStudentMongoRepo : MongoDBRepository<SEOStudent>, ISEOStudentMongoRepo
{
public SEOStudentMongoRepo(IMongoDBRepositoryContext context)
: base(context)
{
} }
}

其中接口IRepository的定义:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks; namespace Frozen.Common.Interface
{
public interface IRepository<T> where T : class
{
void Add(T entity);
void AddAll(IEnumerable<T> entities);
void Update(T entity);
void Update(IEnumerable<T> entities);
void Delete(T entity);
void Delete(Expression<Func<T, bool>> where);
void DeleteAll(IEnumerable<T> entities); void Clear();
T GetById(long Id);
T GetById(string Id);
T Get(Expression<Func<T, bool>> where);
IEnumerable<T> GetAll();
IEnumerable<T> GetMany(Expression<Func<T, bool>> where);
IEnumerable<T> GetAllLazy();
} }

四、调用示例

             var seoStuRepo = new SEOStudentMongoRepo(new MongoDBRepositoryContext(new MongoDBRepositoryContextSettings()));

             seoStuRepo.Add(new SEOStudent() {
Name = "张冬林"
}); seoStuRepo.Add(new SEOStudent()
{
Name = "张冬林"
}); var seoStu = seoStuRepo.Get(p => p.Name=="张冬林"); Console.ReadKey();

五、Web API 调用示例

1、IOC注册

             #region mongoDB
builder.RegisterType<MongoDBRepositoryContextSettings>().As<IMongoDBRepositoryContextSettings>().SingleInstance();
builder.RegisterType<MongoDBRepositoryContext>().As<IMongoDBRepositoryContext>().SingleInstance();
builder.RegisterAssemblyTypes(typeof(SEOStudentMongoRepo).Assembly)
.Where(t => t.Name.EndsWith("MongoRepo"))
.AsImplementedInterfaces().InstancePerLifetimeScope();
#endregion

2、Controller调用

         private readonly ICommandBus _commandBus;
private readonly ISEOStudentMongoRepo _seoStudentMongoRepo; public StudentController(ICommandBus commandBus, ISEOStudentMongoRepo seoStudentMongoRepo)
{
this._commandBus = commandBus;
this._seoStudentMongoRepo = seoStudentMongoRepo;
}
             _seoStudentMongoRepo.Add(new SEOStudent()
{
Name = "张冬林"
}); _seoStudentMongoRepo.Add(new SEOStudent()
{
Name = "张冬林"
}); var seoStu = _seoStudentMongoRepo.Get(p => p.Name == "张冬林");

结果截图:

MongoDB数据仓储的更多相关文章

  1. 从零开始,搭建博客系统MVC5+EF6搭建框架(1),EF Code frist、实现泛型数据仓储以及业务逻辑

    前言      从上篇30岁找份程序员的工作(伪程序员的独白),文章开始,我说过我要用我自学的技术,来搭建一个博客系统,也希望大家给点意见,另外我很感谢博客园的各位朋友们,对我那篇算是自我阶段总结文章 ...

  2. mongoDB 数据导出与导入

    一.导出 命令格式:在mongodb/bin目录下 mongoexport -h IP --port 端口 -u 用户名 -p 密码 -d 数据库 -c 表名 -f 字段 -q 条件导出 --csv ...

  3. MongoDB副本集配置系列十一:MongoDB 数据同步原理和自动故障转移的原理

    1:数据同步的原理: 当Primary节点完成数据操作后,Secondary会做出一系列的动作保证数据的同步: 1:检查自己local库的oplog.rs集合找出最近的时间戳. 2:检查Primary ...

  4. mongodb数据文件内部结构

    有人在Quora上提问:MongoDB数据文件内部的组织结构是什么样的.随后10gen的工程师Jared Rosoff出来做了简短的回答. 每一个数据库都有自己独立的文件.如果你开启了director ...

  5. 用elasticsearch索引mongodb数据

    参照网页:单机搭建elasticsearch和mongodb的river 三个步骤: 一,搭建单机replicSet二,安装mongodb-river插件三,创建meta,验证使用 第一步,搭建单机m ...

  6. MongoDB学习笔记(三) 在MVC模式下通过Jqgrid表格操作MongoDB数据

    看到下图,是通过Jqgrid实现表格数据的基本增删查改的操作.表格数据增删改是一般企业应用系统开发的常见功能,不过不同的是这个表格数据来源是非关系型的数据库MongoDB.nosql虽然概念新颖,但是 ...

  7. Mongodb数据备份恢复

    Mongodb数据备份恢复 一.MongoDB数据库导入导出操作 1.导出数据库 twangback为备份的文件夹 命令: mongodump -h 127.0.0.1[服务器IP] -d advie ...

  8. 通过logstash-input-mongodb插件将mongodb数据导入ElasticSearch

    目的很简单,就是将mongodb数据导入es建立相应索引.数据是从特定的网站扒下来,然后进行二次处理,也就是数据去重.清洗,接着再保存到mongodb里,那么如何将数据搞到ElasticSearch中 ...

  9. docker备份mongodb数据,导入导出

    场景:服务器要升级,之前在linux部署的mongodb没有用docker,升级后,mongodb要用docker部署,并将原有的mongodb数据导入到docker部署的mongodb中. 1.在l ...

随机推荐

  1. UWP 中的 LaunchUriAsync,使用默认浏览器或其他应用打开链接

    古老的 Win32 应用启动其他程序太过方便,以至于一部分开发者都已经不记得 Windows 能通过关联协议的方式通过统一资源定位符(URI)来启动应用程序了. 转到 UWP 后,使用 URI 启动应 ...

  2. System.IO.Pipelines来对消息进行Buffer合并

    System.IO.Pipelines来对消息进行Buffer合并 https://www.cnblogs.com/smark/p/9927455.html .net core使用Pipelines进 ...

  3. PHP 读取和导出 CSV文件

    PHP 读取和导出 CSV文件,速度比phpexcel快80%,而phpexcel 占内存,在数据大的情况下,5万条只需几秒不到,几乎感觉不出来 如果遇到数字是科学计算法,可以在前面加一个 ' 单引号 ...

  4. Python Tkinter 学习历程 一

    一丶一个简单的程序 from tkinter import * #引入所有类#查看tk版本#tkinter._test() root = Tk(); #对这个类进行实例化 w1 = Label(roo ...

  5. 重温CLR(十五) 托管堆和垃圾回收

    本章要讨论托管应用程序如何构造新对象,托管堆如何控制这些对象的生存期,以及如何回收这些对象的内存.简单地说,本章要解释clr中的垃圾回收期是如何工作的,还要解释相关的性能问题.另外,本章讨论了如何设计 ...

  6. 在IIS上搭建FTP服务

    FTP服务 FTP是文件传输协议(File Transfer Protocol)的简称,该协议属于应用层协议(端口号通常为21),用于Internet上的双向文件传输(即文件的上传和下载).在网络上有 ...

  7. vs2013环境下boost配置

    编译boost库的过程这里暂时不写.  先写在vs2013下的boost配置. 新建一个工程, 1, 属性->C/C++,在附加包含目录添加或编辑Boost的文件路径, D:\boost_1_5 ...

  8. [Drools]JAVA规则引擎 -- Drools- 转http://blog.csdn.net/quzishen/article/details/6163012

    [Drools]JAVA规则引擎 -- Drools 标签: java引擎exceptiongetterstringsetter 2011-01-25 14:33 113340人阅读 评论(35) 收 ...

  9. 从数据库导出数据到excel之List<map>导出

    说明:很多时候取出来的数据是封装为List<Map<String,Object>>,可以直接导出excel表格 项目说明就在 “上一篇” 直接上代码(数据层和业务层不用说了,查 ...

  10. elixir 几种安装方式

    1. yum yum 源(直接放弃,版本太老)   2. 使用预编译包 wget https://github.com/elixir-lang/elixir/releases/download/v1. ...