前提说明:

本编文章所属的微服务框架代码和对mongo支持的代码全部放在github,地址:https://github.com/PeyShine/Demo.MicroServer
另外,如果不知道怎么安装mongodb可以看这篇:http://liuthing.com/2020/05/13/dockerinstallmongodb/

1.依赖

在数据仓储层Demo.MicroServer.Repository,添加Mongo依赖包:dotnet add package MongoDB.Driver

2.封装

编写mongo常用的一些接口以及接口的实现,后续可以根据实际开发情况再进行更多接口的封装

/// <summary>
/// mongoDB服务
/// </summary>
public interface IMongoService
{
    /// <summary>
    /// 新增记录
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="t"></param>
    /// <param name="mongoTable"></param>
    /// <returns></returns>
    int Add<T>(T t, string mongoTable = null);
    /// <summary>
    /// 异步-新增记录
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="t"></param>
    /// <param name="mongoTable"></param>
    /// <returns></returns>
    Task<int> AddAsync<T>(T t, string mongoTable = null);
    /// <summary>
    /// 根据过滤条件获取数量
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="filter"></param>
    /// <param name="mongoTable"></param>
    /// <returns></returns>
    long Count<T>(FilterDefinition<T> filter, string mongoTable = null);
    /// <summary>
    /// 异步-根据过滤条件获取数量
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="filter"></param>
    /// <param name="mongoTable"></param>
    /// <returns></returns>
    Task<long> CountAsync<T>(FilterDefinition<T> filter, string mongoTable = null);
    /// <summary>
    /// 分页获取数据
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="filter"></param>
    /// <param name="pageIndex"></param>
    /// <param name="pageSize"></param>
    /// <param name="field"></param>
    /// <param name="sort"></param>
    /// <param name="mongoTable"></param>
    /// <returns></returns>
    List<T> FindListByPage<T>(FilterDefinition<T> filter, int pageIndex, int pageSize, string[] field = null, SortDefinition<T> sort = null, string mongoTable = null);
    /// <summary>
    /// 异步-分页获取数据
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="filter"></param>
    /// <param name="pageIndex"></param>
    /// <param name="pageSize"></param>
    /// <param name="field"></param>
    /// <param name="sort"></param>
    /// <param name="mongoTable"></param>
    /// <returns></returns>
    Task<List<T>> FindListByPageAsync<T>(FilterDefinition<T> filter, int pageIndex, int pageSize, string[] field = null, SortDefinition<T> sort = null, string mongoTable = null);
}
public class MongoService: IMongoService
{
    private readonly MongoClient _mongoClient;

    private IMongoDatabase _mongoDatabase;

    private string _mongoTable;

    public MongoService(IConfiguration configuration)
    {
        _mongoClient = new MongoClient(configuration["MongoDB.DefaultConnection"]);
        _mongoDatabase = _mongoClient.GetDatabase(configuration["MongoDB.DefaultDatabase"]);
        _mongoTable = configuration["MongoDB.DefaultTable"];
    }

    public int Add<T>(T t,string mongoTable = null)
    {
        try
        {
            if (!string.IsNullOrEmpty(mongoTable))
                _mongoTable = mongoTable;

            var _tb = _mongoDatabase.GetCollection<T>(_mongoTable).WithReadPreference(ReadPreference.PrimaryPreferred);
            _tb.InsertOne(t);
            return 1;
        }
        catch
        {
            return 0;
        }
    }

    public async Task<int> AddAsync<T>(T t, string mongoTable = null)
    {
        try
        {
            if (!string.IsNullOrEmpty(mongoTable))
                _mongoTable = mongoTable;

            var _tb = _mongoDatabase.GetCollection<T>(_mongoTable).WithReadPreference(ReadPreference.PrimaryPreferred);

            await _tb.InsertOneAsync(t);
            return 1;
        }
        catch
        {
            return 0;
        }
    }

    public long Count<T>(FilterDefinition<T> filter, string mongoTable = null)
    {
        try
        {
            if (!string.IsNullOrEmpty(mongoTable))
                _mongoTable = mongoTable;

            var _tb = _mongoDatabase.GetCollection<T>(_mongoTable).WithReadPreference(ReadPreference.PrimaryPreferred);
            return _tb.CountDocuments(filter);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    public async Task<long> CountAsync<T>(FilterDefinition<T> filter, string mongoTable = null)
    {
        try
        {
            if (!string.IsNullOrEmpty(mongoTable))
                _mongoTable = mongoTable;

            var _tb = _mongoDatabase.GetCollection<T>(_mongoTable).WithReadPreference(ReadPreference.PrimaryPreferred);
            return await _tb.CountDocumentsAsync(filter);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    public List<T> FindListByPage<T>(FilterDefinition<T> filter, int pageIndex=1, int pageSize=20, string[] field = null, SortDefinition<T> sort = null, string mongoTable = null)
    {
        try
        {
            if (!string.IsNullOrEmpty(mongoTable))
                _mongoTable = mongoTable;

            var _tb = _mongoDatabase.GetCollection<T>(_mongoTable).WithReadPreference(ReadPreference.PrimaryPreferred);

            //不指定查询字段
            if (field == null || field.Length == 0)
            {
                if (sort == null) return _tb.Find(filter).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToList();
                //进行排序
                return _tb.Find(filter).Sort(sort).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToList();
            }

            //制定查询字段
            var fieldList = new List<ProjectionDefinition<T>>();
            for (int i = 0; i < field.Length; i++)
            {
                fieldList.Add(Builders<T>.Projection.Include(field[i].ToString()));
            }
            var projection = Builders<T>.Projection.Combine(fieldList);
            fieldList?.Clear();

            //不排序
            if (sort == null) return _tb.Find(filter).Project<T>(projection).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToList();

            //排序查询
            return _tb.Find(filter).Sort(sort).Project<T>(projection).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToList();

        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    public async Task<List<T>> FindListByPageAsync<T>(FilterDefinition<T> filter, int pageIndex=1, int pageSize=20, string[] field = null, SortDefinition<T> sort = null, string mongoTable = null)
    {
        try
        {
            if (!string.IsNullOrEmpty(mongoTable))
                _mongoTable = mongoTable;

            var _tb = _mongoDatabase.GetCollection<T>(_mongoTable).WithReadPreference(ReadPreference.PrimaryPreferred);

            //不指定查询字段
            if (field == null || field.Length == 0)
            {
                if (sort == null) return await _tb.Find(filter).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToListAsync();
                //进行排序
                return await _tb.Find(filter).Sort(sort).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToListAsync();
            }

            //制定查询字段
            var fieldList = new List<ProjectionDefinition<T>>();
            for (int i = 0; i < field.Length; i++)
            {
                fieldList.Add(Builders<T>.Projection.Include(field[i].ToString()));
            }
            var projection = Builders<T>.Projection.Combine(fieldList);
            fieldList?.Clear();

            //不排序
            if (sort == null) return await _tb.Find(filter).Project<T>(projection).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToListAsync();

            //排序查询
            return await _tb.Find(filter).Sort(sort).Project<T>(projection).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToListAsync();

        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}

构造函数中的mongodb的配置文件全部读取Apollo配置中心
1

3.在具体使用mongo的微服务实例的Startup文件ConfigureServices中向容器添加接口与实现

services.AddTransient(typeof(IMongoService), typeof(MongoService));

4.编写与mongoDB交互的测试接口

// <summary>
/// 测试从mongodb中获取用户数量
/// </summary>
/// <returns></returns>
[HttpGet]
public async Task<long> GetMongoUserCount()
{
    var list = new List<FilterDefinition<user_mongo>>();
    list.Add(Builders<user_mongo>.Filter.Exists("user_id", true));
    var filter = Builders<user_mongo>.Filter.And(list);
 
     return await _mongoService.CountAsync(filter, "users");
}

5.在mongo中准备两条测试数据

2

6.在swagger中调用接口来测试

3
最后看到输出结果为数量为2,和添加的数量一致。
4


作者:沛山
出处: http://www.liuthing.com
本文版权归作者所有有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。希望能够持续的为大家带来好的技术文章,关注我吧!
公众号:DotNetCore开源学习

在微服务框架Demo.MicroServer中添加SkyWalking+SkyApm-dotnet分布式链路追踪系统 上一篇
在Docker中安装MongoDB 下一篇