Pixiray.AI.Data.Mongodb 0.0.1

dotnet add package Pixiray.AI.Data.Mongodb --version 0.0.1
                    
NuGet\Install-Package Pixiray.AI.Data.Mongodb -Version 0.0.1
                    
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="Pixiray.AI.Data.Mongodb" Version="0.0.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Pixiray.AI.Data.Mongodb" Version="0.0.1" />
                    
Directory.Packages.props
<PackageReference Include="Pixiray.AI.Data.Mongodb" />
                    
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 Pixiray.AI.Data.Mongodb --version 0.0.1
                    
#r "nuget: Pixiray.AI.Data.Mongodb, 0.0.1"
                    
#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 Pixiray.AI.Data.Mongodb@0.0.1
                    
#: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=Pixiray.AI.Data.Mongodb&version=0.0.1
                    
Install as a Cake Addin
#tool nuget:?package=Pixiray.AI.Data.Mongodb&version=0.0.1
                    
Install as a Cake Tool

Pixiray.AI.Data.Mongodb

Build Release NuGet Version NuGet Downloads License: MIT

A high-performance .NET MongoDB repository library with flexible entity support, automatic caching, bulk operations, and comprehensive querying capabilities. Build modern applications without being forced to inherit from base entities.

โœจ Features

  • ๐Ÿ”ฅ Flexible Entity System - Works with POCOs, BsonDocument, and ExpandoObject
  • โšก High Performance - Async-first with parallel operations and buffer optimization
  • ๐Ÿง  Smart Caching - Automatic timestamp-based cache invalidation
  • ๐Ÿ“ฆ Bulk Operations - Efficient bulk insert, update, and delete operations
  • ๐Ÿ” Advanced Querying - LINQ expressions with pattern matching support
  • ๐Ÿ—๏ธ Dependency Injection - First-class DI support with decorator pattern
  • ๐Ÿ“Š Observability - Built-in logging, metrics, and transaction auditing
  • ๐Ÿ”„ Unit of Work - Transaction support with automatic rollback
  • ๐ŸŽฏ Zero Inheritance - No need to inherit from base entity classes

๐Ÿš€ Quick Start

Installation

dotnet add package Pixiray.AI.Data.Mongodb

Basic Setup

using Pixiray.AI.Data.Mongodb.Extensions;

// Configure services
services.AddMongoDbRepositories("mongodb://localhost:27017", "MyDatabase", options =>
{
    options.EnableAutoTimestamps = true;
    options.HandleBsonDocuments = true;
    options.HandleExpandoObjects = true;
});

// Add caching
services.AddRepositoryCaching(TimeSpan.FromMinutes(10));

Simple Entity Example

// No inheritance required!
public class User
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; } = ObjectId.GenerateNewId().ToString();
    
    public string Name { get; set; } = string.Empty;
    public string Email { get; set; } = string.Empty;
    public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
}

// Use in your service
public class UserService
{
    private readonly IRepository<User> _userRepository;
    
    public UserService(IRepository<User> userRepository)
    {
        _userRepository = userRepository;
    }
    
    public async Task<User> CreateUserAsync(string name, string email)
    {
        var user = new User { Name = name, Email = email };
        await _userRepository.InsertAsync(user);
        return user;
    }
    
    public async Task<User?> GetUserAsync(string id)
    {
        return await _userRepository.GetByIdAsync(id); // Cached automatically!
    }
    
    public async Task<IEnumerable<User>> SearchUsersAsync(string searchTerm)
    {
        return await _userRepository.ListAsync(u => u.Name.Contains(searchTerm));
    }
}

๐ŸŽฏ Entity Flexibility

Work with any entity type:

1. Simple POCOs
public class Product
{
    public string Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}
2. BsonDocument (Dynamic)
var document = new BsonDocument
{
    ["_id"] = ObjectId.GenerateNewId(),
    ["name"] = "Dynamic Product",
    ["properties"] = new BsonDocument
    {
        ["color"] = "blue",
        ["size"] = "large"
    }
};

await _bsonRepository.InsertAsync(document);
3. ExpandoObject (Dynamic .NET)
dynamic entity = new ExpandoObject();
entity._id = ObjectId.GenerateNewId().ToString();
entity.name = "Dynamic Entity";
entity.isActive = true;

await _expandoRepository.InsertAsync(entity);

๐Ÿง  Smart Caching

The library automatically manages cache timestamps without requiring inheritance:

// First call - fetches from database and caches
var user = await userRepository.GetByIdAsync("123");

// Second call - returns from cache (much faster!)
var cachedUser = await userRepository.GetByIdAsync("123");

// Update invalidates cache automatically
user.Name = "Updated Name";
await userRepository.UpdateAsync(user);

// Next call fetches fresh data from database
var freshUser = await userRepository.GetByIdAsync("123");

๐Ÿ“ฆ Bulk Operations

Efficient bulk operations for high-throughput scenarios:

// Bulk insert
var users = new List<User> { /* ... */ };
await bulkRepository.BulkInsertAsync(users);

// Bulk update
var updates = users.Select(u => new { Filter = u.Id, Update = u });
await bulkRepository.BulkUpdateAsync(updates);

// Bulk delete
var idsToDelete = new[] { "id1", "id2", "id3" };
await bulkRepository.BulkDeleteAsync(idsToDelete);

๐Ÿ”„ Unit of Work & Transactions

public class OrderService
{
    private readonly IUnitOfWork _unitOfWork;
    
    public async Task ProcessOrderAsync(Order order)
    {
        await _unitOfWork.BeginTransactionAsync();
        
        try
        {
            var userRepo = _unitOfWork.GetRepository<User>();
            var productRepo = _unitOfWork.GetRepository<Product>();
            var orderRepo = _unitOfWork.GetRepository<Order>();
            
            // All operations within the same transaction
            await userRepo.UpdateAsync(order.User);
            await productRepo.UpdateAsync(order.Product);
            await orderRepo.InsertAsync(order);
            
            await _unitOfWork.CommitAsync();
        }
        catch
        {
            await _unitOfWork.RollbackAsync();
            throw;
        }
    }
}

๐Ÿ” Advanced Querying

// Complex LINQ queries
var activeUsers = await repository.ListAsync(u => 
    u.IsActive && 
    u.CreatedAt > DateTime.UtcNow.AddDays(-30) &&
    u.Roles.Contains("Admin"));

// Pattern matching
var users = await repository.ListByPatternAsync("Name", "*john*", PatternType.Wildcard);

// Pagination
var (users, totalCount) = await repository.GetPagedAsync(
    filter: u => u.IsActive,
    pageNumber: 1,
    pageSize: 20,
    orderBy: u => u.CreatedAt);

๐Ÿ“Š Configuration Options

services.AddMongoDbRepositories(connectionString, databaseName, options =>
{
    // Automatic timestamp injection
    options.EnableAutoTimestamps = true;
    options.TimestampFieldName = "__cacheTimestamp";
    
    // Entity type support
    options.HandleBsonDocuments = true;
    options.HandleExpandoObjects = true;
    
    // Backward compatibility
    options.UseTimestampedEntityFallback = true;
    options.PreserveUserTimestamps = true;
    
    // Exclude specific types from automatic timestamping
    options.ExcludedTypes.Add(typeof(AuditLog));
});

๐Ÿ—๏ธ Architecture

The library follows clean architecture principles with:

  • Repository Pattern - Simple, testable data access
  • Decorator Pattern - Composable features (caching, retry, logging)
  • Dependency Injection - Framework-agnostic IoC support
  • Async/Await - Non-blocking operations throughout
  • Interface Segregation - Focused, single-responsibility interfaces

๐Ÿ“š Documentation

๐Ÿงช Testing

# Run tests
dotnet test

# Run with coverage
dotnet test --collect:"XPlat Code Coverage"

๐Ÿค Contributing

We welcome contributions! Please see our Contributing Guide for details.

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests
  5. Submit a pull request

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

๐Ÿ™‹โ€โ™‚๏ธ Support

๐ŸŽฏ Roadmap

  • Redis caching support
  • GraphQL integration
  • More database providers
  • Performance optimizations
  • Additional bulk operations

Built with โค๏ธ by Pixiray AI

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

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.0.1 436 7/24/2025