| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899 |
- using Business.Core.Attributes;
- using Microsoft.Extensions.Options;
- using MongoDB.Bson;
- using MongoDB.Driver;
- using MongoDB.Driver.Linq;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using Volo.Abp.Domain.Entities;
- namespace Business.Core.MongoDBHelper
- {
- /// <summary>
- /// MongoDB帮助类
- /// </summary>
- public class MongoDBTools<T> : IMongoDB<T> where T : Entity<long>
- {
- public readonly IMongoCollection<T> mongoCollection;
- public IOptionsSnapshot<Config> _config;
- /// <summary>
- /// MongoDB链接
- /// </summary>
- /// <param name="config"></param>
- /// <exception cref="NotImplementedException"></exception>
- public MongoDBTools(IOptionsSnapshot<Config> config)
- {
- _config = config;
- //数据库链接
- MongoClient client = new MongoClient(config.Value.connectstring);
- CollectionNameAttribute collectonName = typeof(T).GetCustomAttributes(typeof(CollectionNameAttribute), true).FirstOrDefault() as CollectionNameAttribute;
- if (collectonName == null)
- {
- throw new NotImplementedException("请配置Attribute属性!");
- }
- //数据库
- var database = client.GetDatabase(collectonName.DatabaseName);
- //表名
- mongoCollection = database.GetCollection<T>(collectonName.CollectionName);
- }
- /// <summary>
- /// 插入一条数据
- /// </summary>
- /// <param name="document"></param>
- /// <returns></returns>
- public Task InsertOne(T document)
- {
- return mongoCollection.InsertOneAsync(document);
- }
- /// <summary>
- /// 插入多条数据
- /// </summary>
- /// <param name="documents"></param>
- /// <returns></returns>
- /// <exception cref="NotImplementedException"></exception>
- public Task InsertMany(List<T> documents)
- {
- return mongoCollection.InsertManyAsync(documents,new InsertManyOptions() { IsOrdered = false});
- }
- /// <summary>
- /// 更新一条数据
- /// </summary>
- /// <param name="documents"></param>
- /// <param name="id"></param>
- /// <returns></returns>
- public Task<ReplaceOneResult> UpdateOne(T documents,long id)
- {
- return mongoCollection.ReplaceOneAsync(Builders<T>.Filter.Eq(p=>p.Id, id), documents);
- }
- /// <summary>
- /// 获取所有数据
- /// </summary>
- /// <returns></returns>
- /// <exception cref="NotImplementedException"></exception>
- public Task<List<T>> GetAll()
- {
- return mongoCollection.AsQueryable<T>().ToListAsync();
- }
- /// <summary>
- /// 跟据Id获取数据
- /// </summary>
- /// <param name="id"></param>
- /// <returns></returns>
- /// <exception cref="NotImplementedException"></exception>
- public Task<T> GetOneByID(long id)
- {
- return mongoCollection.Find(p => p.Id == id).FirstOrDefaultAsync();
- }
- }
- }
|