MongoDB数据仓储
本篇是作为另一篇随笔的一部分‘搭建一个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数据仓储的更多相关文章
- 从零开始,搭建博客系统MVC5+EF6搭建框架(1),EF Code frist、实现泛型数据仓储以及业务逻辑
前言 从上篇30岁找份程序员的工作(伪程序员的独白),文章开始,我说过我要用我自学的技术,来搭建一个博客系统,也希望大家给点意见,另外我很感谢博客园的各位朋友们,对我那篇算是自我阶段总结文章 ...
- mongoDB 数据导出与导入
一.导出 命令格式:在mongodb/bin目录下 mongoexport -h IP --port 端口 -u 用户名 -p 密码 -d 数据库 -c 表名 -f 字段 -q 条件导出 --csv ...
- MongoDB副本集配置系列十一:MongoDB 数据同步原理和自动故障转移的原理
1:数据同步的原理: 当Primary节点完成数据操作后,Secondary会做出一系列的动作保证数据的同步: 1:检查自己local库的oplog.rs集合找出最近的时间戳. 2:检查Primary ...
- mongodb数据文件内部结构
有人在Quora上提问:MongoDB数据文件内部的组织结构是什么样的.随后10gen的工程师Jared Rosoff出来做了简短的回答. 每一个数据库都有自己独立的文件.如果你开启了director ...
- 用elasticsearch索引mongodb数据
参照网页:单机搭建elasticsearch和mongodb的river 三个步骤: 一,搭建单机replicSet二,安装mongodb-river插件三,创建meta,验证使用 第一步,搭建单机m ...
- MongoDB学习笔记(三) 在MVC模式下通过Jqgrid表格操作MongoDB数据
看到下图,是通过Jqgrid实现表格数据的基本增删查改的操作.表格数据增删改是一般企业应用系统开发的常见功能,不过不同的是这个表格数据来源是非关系型的数据库MongoDB.nosql虽然概念新颖,但是 ...
- Mongodb数据备份恢复
Mongodb数据备份恢复 一.MongoDB数据库导入导出操作 1.导出数据库 twangback为备份的文件夹 命令: mongodump -h 127.0.0.1[服务器IP] -d advie ...
- 通过logstash-input-mongodb插件将mongodb数据导入ElasticSearch
目的很简单,就是将mongodb数据导入es建立相应索引.数据是从特定的网站扒下来,然后进行二次处理,也就是数据去重.清洗,接着再保存到mongodb里,那么如何将数据搞到ElasticSearch中 ...
- docker备份mongodb数据,导入导出
场景:服务器要升级,之前在linux部署的mongodb没有用docker,升级后,mongodb要用docker部署,并将原有的mongodb数据导入到docker部署的mongodb中. 1.在l ...
随机推荐
- BZOJ5297 CQOI2018 社交网络 【矩阵树定理Matrix-Tree】
BZOJ5297 CQOI2018 社交网络 Description 当今社会,在社交网络上看朋友的消息已经成为许多人生活的一部分.通常,一个用户在社交网络上发布一条消息(例如微博.状态.Tweet等 ...
- 在 GitHub 公开仓库中隐藏自己的私人邮箱地址
GitHub 重点在开方源代码,其本身还是非常注重隐私的.这一点与面向企业的 GitLab 很不一样. 不过,你依然可能在 GitHub 上泄露隐私信息,例如企业内部所用的电子邮箱. GitHub 对 ...
- MySQL优化之表结构优化的5大建议
很多人都将 数据库设计范式 作为数据库表结构设计“圣经”,认为只要按照这个范式需求设计,就能让设计出来的表结构足够优化,既能保证性能优异同时还能满足扩展性要求殊不知,在N年前被奉为“圣经”的数据库设计 ...
- nomad 安装(单机)试用
备注: nomad 可以实现基础设施的调度管理,类似kubernetes ,但是在多云以及多平台支持上比较好, 还是hashicrop 工具出品的,很不错,同时本地测试因为使用默认的 ...
- vault key 管理工具
Vault is a tool for securely accessing secrets. A secret is anything that you want to tightly contro ...
- MyEclipse中将普通Java项目convert(转化)为Maven项目
在MyEclipse10中将Maven项目转成普通Java项目后,想将Java项目转成Maven项目,结果一下子傻眼了.根本就没有攻略中提到的config标签.仔细一看,喵咪的,人家用的是Eclips ...
- 使用Maven运行Solr(翻译)
Solr是一个使用开源的搜索服务器,它采用Lucene Core的索引和搜索功能构建,它可以用于几乎所有的编程语言实现可扩展的搜索引擎. Solr的虽然有很多优点,建立开发环境是不是其中之一.此博客条 ...
- 面试常考知识点——Java(JVM,JDK,JRE)
1. 什么是Java虚拟机?为什么Java被称作是“平台无关的编程语言”? 答:(1)Java虚拟机是一个可以执行Java字节码的虚拟机进程.Java源文件被编译成能被Java虚拟机执行的字节码文件. ...
- NetCore 下集成SignalR并进行分组处理
Tips: 1.注意跟普通版Net.MVC的前端处理方式不一样,以前可以connection.start()后直接done里面再做逻辑处理,现在不行了 建议做法是在具体的业务Hub里重写OnConne ...
- 关于FFT的硬件实现
DFT在实际应用中非常重要,可以计算信号的频谱,功率谱和线性卷积等. 离散傅里叶变换的公式: 其中: 称为旋转因子. 由欧拉公式可得: 直接按DFT变换进行计算,当序列长度N很大时,计算量非常大,所 ...