MongoDbGenericRepository 1.6.3

dotnet add package MongoDbGenericRepository --version 1.6.3                
NuGet\Install-Package MongoDbGenericRepository -Version 1.6.3                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="MongoDbGenericRepository" Version="1.6.3" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add MongoDbGenericRepository --version 1.6.3                
#r "nuget: MongoDbGenericRepository, 1.6.3"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install MongoDbGenericRepository as a Cake Addin
#addin nuget:?package=MongoDbGenericRepository&version=1.6.3

// Install MongoDbGenericRepository as a Cake Tool
#tool nuget:?package=MongoDbGenericRepository&version=1.6.3                

MongoDbGenericRepository

An example of generic repository implementation using the MongoDB C# Sharp 2.0 driver (async)

Now available as a nuget package: https://www.nuget.org/packages/MongoDbGenericRepository/

Covered by 400+ integration tests and counting.

The MongoDbGenericRepository is also used in AspNetCore.Identity.MongoDbCore.

Support This Project

If you have found this project helpful, either as a library that you use or as a learning tool, please consider buying Alex a coffee: <a href="https://www.buymeacoffee.com/zeitquest" target="_blank"><img height="40px" src="https://cdn.buymeacoffee.com/buttons/default-orange.png" alt="Buy Me A Coffee" style="max-height: 51px;width: 150px !important;" ></a>

Worth Knowing

This package sets the MongoDefaults.GuidRepresentation to MongoDB.Bson.GuidRepresentation.Standard by default, instead of the default driver setting of MongoDB.Bson.GuidRepresentation.CSharpLegacy. This can cause issues if you have been using the driver on an existing application previously or if you are using CosmosDB.

You can override this behaviour to enforce legacy behaviour in your app Startup routine like so :

MongoDbContext.SetGuidRepresentation(MongoDB.Bson.GuidRepresentation.CSharpLegacy). More info here.

Usage examples

This repository is meant to be inherited from.

You are responsible for managing its lifetime, it is advised to setup this repository as a singleton.

Here is an example of repository usage, where the TestRepository is implementing 2 custom methods:

    public interface ITestRepository : IBaseMongoRepository
    {
        void DropTestCollection<TDocument>();
        void DropTestCollection<TDocument>(string partitionKey);
    }
    
    public class TestRepository : BaseMongoRepository, ITestRepository
    {
        public TestRepository(string connectionString, string databaseName) : base(connectionString, databaseName)
        {
        }

        public void DropTestCollection<TDocument>()
        {
            MongoDbContext.DropCollection<TDocument>();
        }

        public void DropTestCollection<TDocument>(string partitionKey)
        {
            MongoDbContext.DropCollection<TDocument>(partitionKey);
        }
    }

If all your documents have the same type of Id, you can use the more specific BaseMongoRepository<TKey> where TKey is the type of the Id of your documents.

    public class TestTKeyRepository<TKey> : BaseMongoRepository<TKey>, ITestRepository<TKey> where TKey : IEquatable<TKey>
    {
        const string connectionString = "mongodb://localhost:27017/MongoDbTests";
        private static readonly ITestRepository<TKey> _instance = new TestTKeyRepository<TKey>(connectionString);
        /// <inheritdoc />
        private TestTKeyRepository(string connectionString) : base(connectionString)
        {
        }
    }

Instantiation

The repository can be instantiated like so:

ITestRepository testRepository = new TestRepository(connectionString, "MongoDbTests");
ITestRepository<TKey> testTKeyRepository = new TestTKeyRepository<TKey>(connectionString);

If you prefer to reuse the same MongoDb database across your application, you can use the MongoDatabase from the MongoDb driver implementing the IMongoDatabase interface:

var client = new MongoClient(connectionString);
var mongoDbDatabase = Client.GetDatabase(databaseName);
ITestRepository testRepository = new TestRepository(mongoDbDatabase);

Adding documents

To add a document, its class must inherit from the Document class, implement the IDocument or IDocument<TKey> interface:

    public class MyDocument : Document
    {
        public MyDocument()
        {
            Version = 2; // you can bump the version of the document schema if you change it over time
        }
        public string SomeContent { get; set; }
    }

The IDocument and IDocument<TKey> interfaces can be seen below:

    /// <summary>
    /// This class represents a basic document that can be stored in MongoDb.
    /// Your document must implement this class in order for the MongoDbRepository to handle them.
    /// </summary>
    public interface IDocument
    {
        Guid Id { get; set; }
        int Version { get; set; }
    }
    
    /// <summary>
    /// This class represents a basic document that can be stored in MongoDb.
    /// Your document must implement this class in order for the MongoDbRepository to handle them.
    /// </summary>
    public interface IDocument<TKey> where TKey : IEquatable<TKey>
    {
        /// <summary>
        /// The Primary Key, which must be decorated with the [BsonId] attribute 
        /// if you want the MongoDb C# driver to consider it to be the document ID.
        /// </summary>
        [BsonId]
        TKey Id { get; set; }
        /// <summary>
        /// A version number, to indicate the version of the schema.
        /// </summary>
        int Version { get; set; }
    }

Partitioned collections

This repository also allows you to partition your document across multiple collections, this can be useful if you are running a SaaS application and want to keep good performance.

To use partitioned collections, you must define your documents using the PartitionedDocument class, which implements the IPartitionedDocument interface:

    public class MyPartitionedDocument : PartitionedDocument
    {
        public MyPartitionedDocument(string myPartitionKey) : base(myPartitionKey)
        {
            Version = 1;
        }
        public string SomeContent { get; set; }
    }

This partitioned key will be used as a prefix to your collection name. The collection name is derived from the name of the type of your document, is set to camel case, and is pluralized using a class taken from Humanizer (https://github.com/Humanizr/Humanizer).

var myDoc = new MyPartitionedDocument("myPartitionKey");
_testRepository.AddOne(myDoc);

The above code will generate a collection named myPartitionKey-myPartitionedDocuments.

CollectionName Attribute

It is now possible to change the collection name by using the CollectionName attribute:

    [CollectionName("MyCollectionName")]
    public class MyDocument : Document
    {
        public MyDocument()
        {
            Version = 2;
        }
        public string SomeContent { get; set; }
    }

Documents of this type will be inserted into a collection named "MyCollectionName".

Index Management

From version 1.3.8 the MongoDbGenericRepository implements the IBaseMongoRepository_Index and IBaseMongoRepository_Index<TKey> interfaces. This exposes the functionality to programmatically manage indexes against your collections in a generic fashion.

The following methods are exposed and fully integration tested:

  • CreateAscendingIndexAsync
  • CreateDescendingIndexAsync
  • CreateCombinedTextIndexAsync
  • CreateHashedIndexAsync
  • CreateTextIndexAsync
  • DropIndexAsync
  • GetIndexesNamesAsync

Usage examples:

	string expectedIndexName = $"myCustomIndexName";
	var option = new IndexCreationOptions
	{
		Name = expectedIndexName
	};
	// Act
	// create a text index against the Version property of the document.
	var result = await SUT.CreateTextIndexAsync<T, TKey>(x => x.Version, option, PartitionKey);

	// Assert
	var listOfIndexNames = await SUT.GetIndexesNamesAsync<T, TKey>(PartitionKey);
	Assert.Contains(expectedIndexName, listOfIndexNames);

	// Cleanup
	await SUT.DropIndexAsync<T, TKey>(expectedIndexName, PartitionKey);

Please refer to the IntegrationTests (NET45) and CoreIntegrationTests (netstandard2.0) projects for more usage examples. The CoreIntegrationTests.Infrastructure.MongoDbTKeyDocumentTestBase<T, TKey> test class is a good start.

Author

Alexandre Spieser

License

mongodb-generic-repository is under MIT license - http://www.opensource.org/licenses/mit-license.php

The MIT License (MIT)

Copyright (c) 2016-2019 Alexandre Spieser

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

==============================================================================

Inflector (https://github.com/srkirkland/Inflector) The MIT License (MIT) Copyright (c) 2013 Scott Kirkland

==============================================================================

Humanizer (https://github.com/Humanizr/Humanizer) The MIT License (MIT) Copyright (c) 2012-2014 Mehdi Khalili (http://omar.io)

==============================================================================

Copyright © 2019

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 is compatible. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 is compatible.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (31)

Showing the top 5 NuGet packages that depend on MongoDbGenericRepository:

Package Downloads
AspNetCore.Identity.MongoDbCore

A MongoDb UserStore and RoleStore adapter for Microsoft.Extensions.Identity.Core 6.0.

Brainix.Common.Classes

Package Description

NetPro.MongoDb

Package Description

Brainix.Common.Classes-v2

Package Description

LShared.Frameworks

Package Description

GitHub repositories (2)

Showing the top 2 popular GitHub repositories that depend on MongoDbGenericRepository:

Repository Stars
alexandre-spieser/AspNetCore.Identity.MongoDbCore
A MongoDb UserStore and RoleStore adapter for Microsoft.AspNetCore.Identity 2.2. Allows you to use MongoDb instead of SQL server with Microsoft.AspNetCore.Identity 2.2. (not Identity 3.0)
LeonKou/NetPro
🌈An enhanced version with clean architecture of asp.netcore,efficiently manage startup,Support for netcore3.1/6.0
Version Downloads Last updated
1.6.3 541 12/8/2024
1.6.2 2,523 11/23/2024
1.6.1 30,222 5/28/2024
1.6.0 58,152 8/11/2023
1.5.1 1,781 8/2/2023
1.5.0 1,307 8/1/2023
1.4.8 824,762 10/13/2021
1.4.7 68,705 3/15/2021
1.4.6 5,579 3/15/2021
1.4.5 49,411 6/9/2020
1.4.4 2,957 6/6/2020
1.4.3 443,153 2/5/2020
1.4.2 1,891 2/5/2020
1.4.1 129,840 11/18/2019
1.4.0 91,690 4/18/2019
1.3.9 2,352 4/14/2019
1.3.8 104,417 10/7/2018
1.3.7 4,461 9/9/2018
1.3.6 20,391 3/6/2018
1.3.5 2,870 2/10/2018
1.3.4 4,631 1/27/2018
1.3.3 2,520 11/19/2017
1.3.2 2,293 11/1/2017
1.3.1 2,255 11/1/2017
1.3.0 4,405 10/1/2017
1.2.1 2,246 9/23/2017
1.2.0 2,267 9/9/2017
1.1.0 2,270 9/3/2017
1.0.0 2,477 9/3/2017