本篇是作为另一篇随笔的一部分‘搭建一个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. WPF 同一窗口内的多线程 UI(VisualTarget)

    WPF 的 UI 逻辑只在同一个线程中,这是学习 WPF 开发中大家几乎都会学习到的经验.如果希望做不同线程的 UI,大家也会想到使用另一个窗口来实现,让每个窗口拥有自己的 UI 线程.然而,就不能让 ...

  2. linux 系统下配置java环境变量

    liunx桌面版本系统下载地址:http://www.ubuntukylin.com/downloads/ 1.源码包准备: 首先到官网下载jdk,http://www.oracle.com/tech ...

  3. springboot: 集成jdbc

    1.pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www ...

  4. jsp转向,exception

    jsp要像servlet那样转向时可以得 <jsp:forward page="Counter.jsp"> <jsp:param name="parma ...

  5. MyEclipse中将普通Java项目convert(转化)为Maven项目

    在MyEclipse10中将Maven项目转成普通Java项目后,想将Java项目转成Maven项目,结果一下子傻眼了.根本就没有攻略中提到的config标签.仔细一看,喵咪的,人家用的是Eclips ...

  6. 通过修改注册表建立Windows自定义协议

    引言 本文主要介绍注册表的概念与其相关根项的功能,以及浏览器如何通过连接调用自定义协议并与客户端进行数据通信.文中讲及如何通过C#程序.手动修改.安装项目等不同方式对注册表进行修改.其中通过安装项目对 ...

  7. xsd解析

    1. 解释: <xsd:element name="interceptors"> <xsd:annotation> 这一块是对第一行的注解(解释) < ...

  8. (转)Inno Setup入门(十四)——替换安装程序和卸载程序的图标

    本文转载自:http://blog.csdn.net/yushanddddfenghailin/article/details/17250937 通常Inno生成的安装文件的图标是一个光盘和显示器,如 ...

  9. Django 组件-用户认证

    用户认证 auth模块 from django.contrib import auth 1.1 .authenticate()  提供了用户认证,即验证用户名以及密码是否正确,一般需要username ...

  10. ptyhon中文本挖掘精简版

    import xlrd import jieba import sys import importlib import os #python内置的包,用于进行文件目录操作,我们将会用到os.listd ...