DataMagic.MongoDatabase 9.1.0

dotnet add package DataMagic.MongoDatabase --version 9.1.0
                    
NuGet\Install-Package DataMagic.MongoDatabase -Version 9.1.0
                    
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="DataMagic.MongoDatabase" Version="9.1.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="DataMagic.MongoDatabase" Version="9.1.0" />
                    
Directory.Packages.props
<PackageReference Include="DataMagic.MongoDatabase" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add DataMagic.MongoDatabase --version 9.1.0
                    
#r "nuget: DataMagic.MongoDatabase, 9.1.0"
                    
#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.
#:package DataMagic.MongoDatabase@9.1.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=DataMagic.MongoDatabase&version=9.1.0
                    
Install as a Cake Addin
#tool nuget:?package=DataMagic.MongoDatabase&version=9.1.0
                    
Install as a Cake Tool

DataMagic.MongoDatabase

I. Overview

DataMagic.MongoDatabase is an extension package of the DataMagic ecosystem that provides common functions and utilities for MongoDB database queries. This library simplifies working with MongoDB by offering extension methods for filtering, searching, and pagination operations, making it easier to build robust and maintainable data access layers.

The package seamlessly integrates with the DataMagic.Abstractions library to provide type-safe, fluent API for MongoDB operations including numeric filtering, date-time comparisons, text searching, and result pagination.

II. Functions

Extensions

DateTimeFilterExtensions

Extension methods for filtering MongoDB queries based on date-time values.

Methods:

  • WithDateTimeSearch<T, TValueType>(IQueryable<T>, Expression<Func<T, TValueType>>, DateTimeFilter)

    • Applies date-time filtering to an IQueryable collection
    • Supports comparison operators: SmallerThan, SmallerThanEqualTo, GreaterThanEqualTo, GreaterThan, Equal
    • Returns: Filtered IQueryable<T>
    • Usage: Filter entities by date fields with specific comparison operators
  • WithDateTimeRangeSearch<T, TValueType>(IQueryable<T>, Expression<Func<T, TValueType>>, DateTimeRangeFilter)

    • Applies date-time range filtering (From/To) to an IQueryable collection
    • Combines multiple date filters for range queries
    • Returns: Filtered IQueryable<T>
    • Usage: Filter entities within a specific date range
  • WithDateTimeSearch<T, TValueType>(FilterDefinitionBuilder<T>, Expression<Func<T, TValueType>>, DateTimeFilter)

    • Creates a MongoDB FilterDefinition for date-time filtering
    • Supports all date-time comparison operators
    • Returns: FilterDefinition<T>
    • Usage: Build complex filter definitions for MongoDB queries
NumericSearchExtensions

Extension methods for filtering MongoDB queries based on numeric values.

Methods:

  • WithNumericSearch<T, TValueType>(IQueryable<T>, Expression<Func<T, TValueType>>, NumericFilter<TValueType>)

    • Applies numeric filtering to an IQueryable collection
    • Supports comparison operators: Equal, SmallerThan, SmallerThanEqualTo, GreaterThanEqualTo, GreaterThan
    • Validates numeric types at runtime
    • Returns: Filtered IQueryable<T>
    • Usage: Filter entities by numeric fields with specific comparison operators
  • WithNumericRangeSearch<T, TValueType>(IQueryable<T>, Expression<Func<T, TValueType>>, NumericRangeFilter<TValueType, TValueType>)

    • Applies numeric range filtering (From/To) to an IQueryable collection
    • Combines multiple numeric filters for range queries
    • Returns: Filtered IQueryable<T>
    • Usage: Filter entities within a specific numeric range
TextSearchExtensions

Extension methods for filtering MongoDB queries based on text values.

Methods:

  • WithTextSearch<T>(FilterDefinitionBuilder<T>, FieldDefinition<T, string>, TextFilter)

    • Creates a MongoDB FilterDefinition for text filtering using field definition
    • Supports text filter modes: Contains, Equal, EndWith, StartWith, EqualIgnoreCase
    • Uses MongoDB regex patterns for flexible text matching
    • Returns: FilterDefinition<T>
    • Usage: Build text-based filter definitions for MongoDB queries
  • WithTextSearch<T>(FilterDefinitionBuilder<T>, Expression<Func<T, object>>, TextFilter)

    • Creates a MongoDB FilterDefinition for text filtering using lambda expression
    • Supports all text filter modes
    • Returns: FilterDefinition<T>
    • Usage: Build text-based filter definitions with type-safe property selectors
SearchResultExtensions

Extension methods for paginating and converting MongoDB queries to search results.

Methods:

  • ToSearchResultAsync<T>(IQueryable<T>, IPager, CancellationToken)

    • Converts an IQueryable to a paginated ISearchResult<T>
    • Handles total record counting and pagination
    • Returns: Task<ISearchResult<T>>
    • Usage: Paginate in-memory or LINQ-based queries
  • ToSearchResultAsync<T, TProjection>(IFindFluent<T, TProjection>, IPager, CancellationToken)

    • Converts a MongoDB IFindFluent query to a paginated search result with projection
    • Supports asynchronous operations
    • Returns: Task<ISearchResult<TProjection>>
    • Usage: Paginate MongoDB find operations with custom projections
  • ToSearchResultAsync<T>(IAggregateFluent<T>, IPager, CancellationToken)

    • Converts a MongoDB aggregation pipeline to a paginated search result
    • Supports complex aggregation queries with pagination
    • Returns: Task<ISearchResult<T>>
    • Usage: Paginate MongoDB aggregation pipeline results
MongoDatabaseOptionsExtensions

Extension methods that turn MongoDatabaseOptions (from DataMagic.Abstractions) into MongoDB driver connection settings. The result is identical to what new MongoClient(connectionString) produces for the equivalent connection string. The results contain the password: never log them.

Methods:

  • ToMongoUrl(MongoDatabaseOptions)

    • Builds a MongoUrl (host, port, TLS, optional database name, replica set, and credentials with authentication database when Username is set)
    • Returns: MongoUrl
    • Throws: ArgumentNullException (null options), ArgumentException (blank Host, or Username set with blank AuthenticationDatabase), ArgumentOutOfRangeException (Port not between 1 and 65535)
    • Usage: new MongoClient(options.ToMongoUrl())
  • ToMongoClientSettings(MongoDatabaseOptions)

    • Builds MongoClientSettings from ToMongoUrl() so settings can be adjusted before creating the client
    • Returns: MongoClientSettings
    • Throws: same as ToMongoUrl()
    • Usage: Customize logging, cluster configuration or timeouts before new MongoClient(settings)

Models

EntityUpdateBuilder<T>

A builder class for constructing MongoDB update definitions in a fluent manner.

Methods:

  • Update<TField>(FieldDefinition<T, TField>, IUpdatableProperty<TField>)

    • Adds an update operation using a field definition
    • Only updates if the property has been modified
    • Returns: EntityUpdateBuilder<T> (for method chaining)
    • Usage: Build update operations for specific fields
  • Update<TField>(Expression<Func<T, TField>>, IUpdatableProperty<TField>)

    • Adds an update operation using a lambda expression
    • Type-safe property selection with modification tracking
    • Returns: EntityUpdateBuilder<T> (for method chaining)
    • Usage: Build update operations with strongly-typed property selectors
  • Build()

    • Combines all update operations into a single UpdateDefinition<T>
    • Returns: UpdateDefinition<T> or null if no updates were added
    • Usage: Generate the final update definition for MongoDB update operations
  • CountUpdatedFields()

    • Returns the number of fields that will be updated
    • Returns: int
    • Usage: Validate or log the number of fields being updated

III. Requirements

Dependencies

The DataMagic.MongoDatabase package requires the following dependencies:

  • DataMagic.Abstractions (Version 1.2.0)

    • Provides core abstractions, interfaces, and models
    • Includes filter models, operators, and pagination interfaces
  • MongoDB.Driver (Version 3.13.0)

    • Official MongoDB driver for .NET
    • Provides MongoDB client, query builders, and LINQ support

Target Framework

  • .NET 9.0 (net9.0)

Installation

To install the package, add it to your project using:

dotnet add package DataMagic.MongoDatabase

Or add the following to your .csproj file:

<PackageReference Include="DataMagic.MongoDatabase" Version="9.1.0" />

Usage Examples

Numeric Filtering

var query = collection.AsQueryable();
var numericFilter = new NumericFilter<int> 
{ 
    Value = 100, 
    Operator = NumericComparisonOperators.GreaterThan 
};
var filtered = query.WithNumericSearch(x => x.Age, numericFilter);

Date-Time Range Filtering

var dateRangeFilter = new DateTimeRangeFilter 
{
    From = new DateTimeFilter 
    { 
        Value = DateTime.Now.AddDays(-30), 
        Operator = DateTimeComparisonOperators.GreaterThanEqualTo 
    },
    To = new DateTimeFilter 
    { 
        Value = DateTime.Now, 
        Operator = DateTimeComparisonOperators.SmallerThanEqualTo 
    }
};
var filtered = query.WithDateTimeRangeSearch(x => x.CreatedDate, dateRangeFilter);

Text Search with Filter Builder

var filter = Builders<User>.Filter
    .WithTextSearch(x => x.Name, new TextFilter 
    { 
        Value = "John", 
        Mode = TextFilterModes.Contains 
    });
var results = await collection.Find(filter).ToListAsync();

Pagination

var pager = new Pager { Page = 1, PageSize = 20 };
var result = await query.ToSearchResultAsync(pager);
// result.Items contains the paginated items
// result.Total contains the total count

Update Builder

var updateBuilder = new EntityUpdateBuilder<User>();
updateBuilder
    .Update(x => x.Name, updatableNameProperty)
    .Update(x => x.Email, updatableEmailProperty);

var updateDefinition = updateBuilder.Build();
if (updateDefinition != null)
{
    await collection.UpdateOneAsync(filter, updateDefinition);
}

Connecting from MongoDatabaseOptions

var client = new MongoClient(options.ToMongoUrl());
var database = client.GetDatabase(options.DatabaseName);

License

Please refer to the repository license file for licensing information.

Contributing

Contributions are welcome! Please ensure all code follows the existing patterns and includes appropriate documentation.

Product Compatible and additional computed target framework versions.
.NET net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (2)

Showing the top 2 NuGet packages that depend on DataMagic.MongoDatabase:

Package Downloads
ApiFeatures.Mqtt.MongoDatabases

Package Description

ApiFeatures.Webhooks.Apis

Comprehensive webhook module for ASP.NET Core applications with request-response pattern, background processing, MongoDB persistence, and flexible trigger/event-based webhook support.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
9.1.0 88 11/3/2026
9.0.0 133 11/2/2026
1.0.1 692 11/23/2025