Mongo Repository - C#
BaseRepository
1 2 3 4 5 6 7 8 9 | public abstract class BaseRepository<T> { private readonly IMongoCollection<T> _collection; public BaseRepository(IMongoConnectionManager connectionManager, string collectionName) { _collection = connectionManager.GetCollection<T>(collectionName) } } |
Mongo Database Operation Types
//FindAsync - GetMany and GetSingle protected async Task<T> GetSingle(FilterDefinition<T> filter, FindOptions<T,T> options = null) { var retval = await _collection.FindAsync(filter, options).ConfigureAwait(false); return retval.FirstOrDefault(); } protected async Task<T> Get(FilterDefinition<T> filter, SortDefinition<T> sort = null) { var retval = await _collection.FindAsync(filter, new FindOptions<T,T>() { Sort = sort }).ConfigureAwait(false); return retval.ToList(); } //CountAsync protected async Task<bool> Exists(FilterDefinition<T> filter) { var count = await _collection.CountAsync(filter).ConfigureAwait(false); return count > 0; } //InsertManyAsync protected async Task Insert(IEnumerable<T> documents) { await _collection.InsertManyAsync(documents).ConfigureAwait(false); } //UpdateManyAsync protected async Task Update(FilterDefinition<T> filter, UpdateDefinition<T> update) { await _collection.UpdateManyAsync(filter, update).ConfigureAwait(false); } //BulkUpdate protected async Task BulkUpdate(List<WriteModel<T>> updates) { await _collection.BulkWriteAsync(updates).ConfigureAwait(false); } //List<WriteModel<T> Builder var updates = new List<WriteModel<T>>(); foreach(var request in requests)- { var filter = Builders<T>.Filter.Eq(_=>_.Id, request.Id); udpates.Add(new ReplaceOneModel<T>(filter, request)); } //DeleteManyAsync protected async Task Delete(FilterDefinition<T> filter) { await _collection.DeleteManyAsync(filter).ConfigureAwait(false); } //AggregateAsync protected async Task<IEnumerable<TOutput> Aggregate<TOutput>(PipelineDefinition<T,TOutput> pipeline) { var options = new AggregateOptions { AllowDiskUse = true}; return (await _collection.AggregateAsync(pipeline, options).ConfigureAwait(false)).ToList(); } //DistinctAsync var filter = new BsonDocument(); var list = await _collection.DistinctAsync<string>("categories", filter); //Other Collection Operations 1. UpdateOneAsync 2. FindOneAndDelete 3. FindOneAndReplace 4. FindOneAndUpdate 5. InsertOneAsync 6. ReplaceOneAsync
Comments
Post a Comment