Skip to main content

Working with MongoDB in .Net Core (Part 2) - Mongo Collection Base



Mongo Repository - C#

Here we introduce an encapsulation called BaseRepository which every other repository created in the application uses to perform Mongo database Operations.

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

Popular posts from this blog

How to clear Visual Studio Cache

How to clear visual studio cache Many times, during development you would face situations where project references are not loaded properly or you get missing/error DLL's. This is because the Component cache gets corrupted randomly and without any warnings. The first option that needs to be done is to clear component cache and restart Visual Studio since the Cache might be holding onto previous DLL versions. Here are the steps on how to clear Visual Studio Cache, Clearing Component Cache: Close all Visual Studio Instances running in your machine. Also, make sure devenv.exe is not running in the Task Manager Delete the Component cache directory - %USERPROFILE%\AppData\Local\Microsoft\VisualStudio\1x.0\ComponentModelCache Restart Visual Studio The above steps should fix the cache issue most of the times, but some times that is not enough and you need to perform the below steps as well. Clearing User's Temp Folder: Open the temp folder in this locatio n -  %USERPROFILE%\AppData\Loc

PCF Health Check Delay - Invocation timeout

In PCF we can set up the health check invocation timeout to execute X seconds after the instance has been created.  But before that, let's understand the PCF Health Check Lifecycle. Stage 1: The application is deployed to PCF Stage 2: When deploying the app, a health check type is specified and optionally a timeout. If a health check type is not specified, then the monitoring process defaults to a port health check Stage 3: Cloud Controller stages, starts, and runs the application Stage 4: Based on the type specified for the app, Cloud Controller configures a health check    that runs periodically for each app instance Stage 5: When Diego starts an app instance, the app health check runs every two seconds until a response indicates that the app instance is healthy or until the health check timeout elapses. The 2-seconds health check interval is not configurable Stage 6: When an app instance becomes healthy, its route is advertised, if applicable.                  Subsequent hea

How to dependency inject to static class

.Net core supports dependency injection. There are many ways that you can inject services like constructor injection, action method injection, property injection. But there will be scenarios where you need to inject dependency services to static classes. For example, injecting services to extension methods. First, create a static class with a one property IServiceProvider type public void ConfigureServices(IServiceCollection services) { services.AddScoped<ILoggerEntry, LoggerEntry>(); services.AddTransient<IMongoRepository, MongoRepository>(); } Second, configure your services in ConfigureServices() method in Startup.cs and define the lifetime of the service instance using either Transient, Scoped or Singleton types. public void ConfigureServices(IServiceCollection services) { services.AddScoped<ILoggerEntry, LoggerEntry>(); services.AddTransient<IMongoRepository, MongoRepository>(); } For the next step to configure the Static class provider proper