Skip to content
Client v5: BLE, BLE Hosting, HTTP, Jobs - Linux, MacOS, & Blazor Support! Full AOT, RX on BLE only & MANY other features! Power up!

Document DB

A lightweight, database-agnostic document store for .NET that turns your database into a schema-free JSON document database with LINQ querying, spatial/geo queries, vector / ANN search, and full AOT/trimming support. Store entire object graphs — nested objects, child collections — as JSON documents. No CREATE TABLE, no ALTER TABLE, no JOINs, no migrations. One API, multiple database providers.

Frameworks
.NET
.NET MAUI
Blazor
ASP.NET
Operating Systems
Android
iOS
Windows
GitHubGitHub stars for shinyorg/DocumentDb
DownloadsNuGet downloads for Shiny.DocumentDb
SQLiteNuGet downloads for Shiny.DocumentDb.Sqlite
SQLCipherNuGet downloads for Shiny.DocumentDb.Sqlite.SqlCipher
SQL ServerNuGet downloads for Shiny.DocumentDb.SqlServer
MySQLNuGet downloads for Shiny.DocumentDb.MySql
PostgreSQLNuGet downloads for Shiny.DocumentDb.PostgreSql
OracleNuGet downloads for Shiny.DocumentDb.Oracle
LiteDBNuGet downloads for Shiny.DocumentDb.LiteDb
CosmosDBNuGet downloads for Shiny.DocumentDb.CosmosDb
MongoDBNuGet downloads for Shiny.DocumentDb.MongoDb
Azure TableNuGet downloads for Shiny.DocumentDb.AzureTable
DynamoDBNuGet downloads for Shiny.DocumentDb.DynamoDb
DuckDBNuGet downloads for Shiny.DocumentDb.DuckDb
DI ExtensionsNuGet downloads for Shiny.DocumentDb.Extensions.DependencyInjection
IndexedDBNuGet downloads for Shiny.DocumentDb.IndexedDb
AI ToolsNuGet downloads for Shiny.DocumentDb.Extensions.AI
OrleansNuGet downloads for Shiny.DocumentDb.Orleans
JSON Schema ValidationNuGet downloads for Shiny.DocumentDb.JsonSchema
Offline Sync (App Data Sync)NuGet downloads for Shiny.DocumentDb.AppDataSync
ODataNuGet downloads for Shiny.DocumentDb.OData
OData (ASP.NET Core host)NuGet downloads for Shiny.DocumentDb.AspNetCore.OData
Aspire (AppHost)NuGet downloads for Shiny.DocumentDb.Aspire.Hosting
Aspire (Client)NuGet downloads for Shiny.DocumentDb.Aspire.Client
Aspire (Orleans)NuGet downloads for Shiny.DocumentDb.Aspire.Orleans
  • Multi-provider — SQLite, SQLCipher (encrypted SQLite), LiteDB, CosmosDB, MongoDB, Azure Table Storage, Amazon DynamoDB, DuckDB, IndexedDB (Blazor WASM), SQL Server, MySQL, PostgreSQL, and Oracle with a single API
  • Zero schema, zero migrations — store objects as JSON documents
  • Fluent query builderstore.Query<User>().Where(u => u.Age > 30).OrderBy(u => u.Name).Paginate(0, 20).ToList() with full LINQ expression support for nested properties, Any(), Count(), string methods, null checks, and captured variables
  • IAsyncEnumerable<T> streaming — yield results one-at-a-time with .ToAsyncEnumerable()
  • Expression-based JSON indexes — up to 30x faster queries on indexed properties
  • SQL-level projections — project into DTOs via .Select() at the database level
  • Aggregates — scalar .Max(), .Min(), .Sum(), .Average() as terminal methods; aggregate projections with automatic GROUP BY via Sql.* markers; collection-level Sum, Min, Max, Average on child collections
  • Ordering.OrderBy(u => u.Age) and .OrderByDescending(u => u.Name) on the fluent query builder
  • Pagination.Paginate(offset, take) translates to SQL LIMIT/OFFSET
  • Table-per-type mappingMapTypeToTable<T>() gives a document type its own dedicated table. Unmapped types share a configurable default table
  • Custom Id propertiesMapTypeToTable<T>("table", x => x.MyProp) to combine with a dedicated table, or MapIdProperty<T>(x => x.MyProp) to override the Id while keeping the type in the default shared table
  • Document diffingGetDiff compares a modified object against the stored document and returns an RFC 6902 JsonPatchDocument<T> with deep nested-object diffing
  • Surgical field updatesSetProperty updates a single JSON field without deserialization. RemoveProperty strips a field. Both support nested paths
  • JSON Merge Patch (Upsert)Upsert uses RFC 7396 json_patch to deep-merge a partial object into an existing document, preserving unset nullable fields. Inserts if the document doesn’t exist
  • Merge-vs-replace flags — pick the write mode explicitly without switching methods: Update(doc, patch: true) deep-merges instead of full-replacing, and Upsert(doc, patchIfUpdate: false) replaces the body wholesale instead of merging. The same flags apply on the late-bound JSON lane (Update(type, jsonObject, patch: true)), which is the precise way to do partial updates. Relational providers + JSON lane; non-default modes throw NotSupportedException on the document-native and key-partitioned stores. Learn more
  • Bulk operationsQuery<T>().Where(...).ExecuteUpdate(x => x.Prop, value) and .ExecuteDelete() issue a single SQL statement against all matching documents — no deserialization, no client-side loop
  • Typed Id lookupsGet, Remove, SetProperty, and RemoveProperty accept the Id as object so you can pass a Guid, int, long, or string directly. Unsupported types throw ArgumentException
  • Late-bound JSON lane — write and read documents by handing the store a registered Type + a JsonNode body, with no CLR Tstore.Insert(type, node) / Update / Upsert (single JsonObject or atomic JsonArray), store.Get(type, id), and store.Query(type, whereClause, parameters) / QueryStream(...) returning raw JsonNodes. The body is stored AS-IS (serialization skipped) but rides the full write pipeline — tenancy, temporal, versioning/CAS, spatial + vector sidecars, interceptors, change notifications. Ideal for generic HTTP intake, message-bus payloads, ETL, and gateways. Relational providers. Learn more
  • Typed DocumentContext — an optional, EF-Core-style typed front-end over IDocumentStore. Declare aggregates on a partial context with [Document(typeof(User), Id = nameof(User.Email), JsonContext = typeof(AppJsonContext))] and a bundled source generator emits a DocumentSet<T> per type plus DI sugar (AddAppContext(...) scoped, AddAppContextFactory(...) for the MAUI/Blazor/desktop story). Work model-first — await db.Users.Where(u => u.Age >= 18).ToList() — with JsonTypeInfo<T> threaded automatically. Ships in core, works over all providers. Learn more
  • Computed properties — map a value derived from other fields (Total = Quantity * UnitPrice, a normalized lower(Email)) that you filter, sort, and project by exactly like a stored property, though it’s never written into the JSON. MapComputedProperty<T>(o => o.Total, o => o.Quantity * o.UnitPrice) runs in alias mode by default (SQL-inlined, zero schema); pass indexed: true on a relational provider to materialize it as a native generated/computed column + index. Recomputed and written back onto the object on read. Fully AOT/trim-safe. Learn more
  • Full AOT/trimming support — all JsonTypeInfo<T> parameters are optional and auto-resolve from a configured JsonSerializerContext. Set UseReflectionFallback = false to catch missing registrations with clear exceptions
  • Optimistic concurrencyMapVersionProperty<T>(x => x.RowVersion) enables automatic version checking on update/upsert. Version is set to 1 on insert, checked and incremented on update. Throws ConcurrencyException on conflict. Works across all providers — stored in the JSON blob with zero schema changes
  • Unit of workCreateUnitOfWork() + SaveChanges() with automatic commit/rollback
  • Batch writesBatchInsert inserts a collection in a single transaction with prepared command reuse, auto-generates IDs, and rolls back atomically on failure. BatchUpsert, BatchUpdate, and BatchRemove<T>(ids) apply many writes as one set operation (a single multi-row INSERT … ON CONFLICT deep-merge on SQLite/DuckDB, one BulkWrite/DeleteMany on MongoDB, parallel request waves on Cosmos, a single DELETE … IN (…) on relational). All-or-nothing — the first version conflict rolls the whole batch back
  • Spatial / geo queries (full OGC geometry) — beyond point-only WithinRadius/WithinBoundingBox/NearestNeighbors, a full Geometry model (GeoLineString, GeoPolygon with holes, multi-geometries) maps via MapSpatialProperty<T>(x => x.Area) and queries with the topological predicate family — GeoIntersects, GeoContains, GeoWithin, GeoCovers, GeoWithinDistance, and friends — returning SpatialResult<T> with DistanceMeters. Compose spatial predicates inside ordinary LINQ with DocumentFunctions.Intersects/Distance/… (server-side, combinable with other Where/OrderBy/paging) and in the string-expression surface too. Backed by a real 2-D spatial index on every SQL provider — SQLite R*Tree, PostgreSQL GiST, MySQL SPATIAL, DuckDB R-Tree, SQL Server spatial index, Oracle SDO_GEOMETRY + MDSYS — plus native ST_* on CosmosDB and 2dsphere on MongoDB. Learn more
  • Vector / ANN search — register an embedding property with MapVectorProperty<T>(d => d.Embedding, dimensions: 1536, metric: VectorDistance.Cosine, indexKind: VectorIndexKind.Hnsw) and query with Query<T>().Where(...).NearestVectors(query, k). Provider-native indexes: pgvector (PostgreSQL), VECTOR + DiskANN (SQL Server 2025), native VECTOR + HNSW/IVF (Oracle 23ai), embedding policy (CosmosDB), $vectorSearch (MongoDB Atlas), vss extension (DuckDB), sqlite-vec (SQLite). Plus AutoEmbedOnInsert<T> to plug in Microsoft.Extensions.AI.IEmbeddingGenerator and embed text automatically on every write. Learn more
  • Full-text search (all providers)MapFullTextProperty<T>(a => a.Body) (or an array of paths) + store.FullTextSearch<T>("orleans persistence") for relevance-ranked search, returning FullTextResult<T> (Document + normalized Score) ordered by relevance, with an optional pre-filter and a fluent store.Query<T>().Where(...).FullTextMatch("...") form. The native index is auto-created and engine-maintained: FTS5 (SQLite), tsvector+GIN (PostgreSQL), FULLTEXT (MySQL), Oracle Text, SQL Server Full-Text, the fts extension (DuckDB), full-text policy (CosmosDB), $text (MongoDB), and an in-memory TF-IDF fallback on LiteDB / IndexedDB. A type must be mapped before it can be searched. Learn more
  • Composite JSON indexesCreateIndexAsync(ctx.User, u => u.Country, u => u.Age) builds a single B-tree across multiple JSON paths on SQLite, SQLCipher, PostgreSQL, MySQL, Oracle, DuckDB, and SQL Server. Learn more
  • Hot backupBackup copies the database to a file. Available on SqliteDocumentStore, SqlCipherDocumentStore, and LiteDbDocumentStore
  • Streaming bulk export / import / restore — the IDocumentBackup store capability moves a whole store’s contents in and out as a portable, streamed v1 backup: ExportAsync(Stream), RestoreAsync(Stream), and the lower-level BulkImportAsync(IAsyncEnumerable<RawDocument>). Bodies bound verbatim (no <T>, no reflection — AOT-friendly); BulkWriteMode picks Insert/Replace/Merge/SkipExisting, with a native bulk-copy fast path (10-100× faster) on PostgreSQL COPY, SQL Server SqlBulkCopy, and DuckDB appender. Every SQL provider plus MongoDB and Cosmos. Learn more
  • Clear the whole store((IDocumentMaintenance)store).ClearAll() wipes every document type plus temporal-history, spatial, and vector sidecars (test/dev resets) without touching the system catalogs. Implemented on the relational DocumentStore (SQLite, SQL Server, PostgreSQL, MySQL, DuckDB, Oracle), MongoDB, and CosmosDB; the older SqliteDocumentStore.ClearAllAsync() delegates to it
  • Database seeding — register IDocumentSeeders to populate initial data once at startup. Schema-free seeding is just idempotent writes, so seeders are provider-agnostic; run-once is versioned via a DocumentSeedMarker (bump Version to re-run). Wire with AddDocumentSeeder<T>() / AddDocumentSeeder(name, version, delegate) at host startup, or call DocumentSeedRunner.RunAsync(store, seeders) directly (e.g. on MAUI)
  • SQLCipher encryption — separate Shiny.DocumentDb.Sqlite.SqlCipher package with AES-256 encryption, password-aware backup, and RekeyAsync to change the encryption key
  • Multi-tenancy — two isolation strategies: shared-table (single database with automatic TenantId column filtering) and tenant-per-database (separate database per tenant via lazy factory). Both resolve the current tenant via a user-implemented ITenantResolver. Consumer code is unchanged — tenant isolation is applied transparently
  • Change monitoring — consume an IAsyncEnumerable<DocumentChange<T>> of insert/update/remove/clear events with await foreach (var c in store.NotifyOnChange<User>(ct)). Filter to a single document with WhenDocumentChanged<T>(id) or to the result set of a fluent query with query.NotifyOnChange(). Buffered in a UnitOfWork and emitted on commit. Learn more
  • Native change feedsIChangeFeedDocumentStore.SubscribeChanges<T> observes all writers via the database’s own mechanism: PostgreSQL LISTEN/NOTIFY triggers, SQL Server Change Tracking (optionally with SqlDependency query notifications), and Cosmos DB native Change Feed. Provisioning is automatic and idempotent
  • Temporal history (system-time versioning)MapTemporal<T>(o => { o.Retention = ...; o.MaxVersions = ...; o.CaptureActor = ...; }) opts a type into append-only versioning. Every Insert/Update/Upsert/Remove/SetProperty/RemoveProperty/BatchInsert records a snapshot to a per-type history sidecar. Read it back with History<T>(id), AsOf<T>(id, when), Restore<T>(id, version), GetDiffBetween<T>(id, from, to), plus fleet-wide AsOfAll<T>(when), ChangesByActor<T>(actor), and ChangesBetween<T>(from, to) — on the ITemporalDocumentStore capability interface, not IDocumentStore. Opt-in per type, on every provider (relational and document/NoSQL). Learn more
  • Global query filters — register an AddQueryFilter<T>(u => !u.IsDeleted) predicate that’s automatically AND-applied to every query of T, plus Get/Update/Remove/SetProperty/RemoveProperty/Clear/ExecuteUpdate/ExecuteDelete and per-query change monitoring. Mirrors Entity Framework Core’s HasQueryFilter, including named filters, IgnoreQueryFilters()/IgnoreQueryFilters("name"), and captured-variable semantics. Learn more
  • AI tool integrationShiny.DocumentDb.Extensions.AI exposes document types as Microsoft.Extensions.AI tool functions for LLM agents. Per-type capability flags (ReadOnly, All), structured filter expressions, field visibility control, and page size caps. Learn more
  • Orleans persistenceShiny.DocumentDb.Orleans provides a full Microsoft Orleans stack — grain storage, reminders, cluster membership, and grain directory — on any DocumentDb backend (relational, MongoDB, or Cosmos) through one IDocumentStore abstraction. Because grain state is persisted as structured, queryable JSON, you can query grain state directly without activating grains (reporting, dashboards, ops tooling) and get a free audit trail of every mutation via MapTemporal<T>. Learn more
  • Telemetry & diagnosticsShiny.DocumentDb.Diagnostics wraps any provider with AddDocumentStoreInstrumentation() to emit OpenTelemetry-native metrics (db.client.operation.duration and friends) and ActivitySource trace spans per operation — CRUD, fluent-query terminals, temporal, and transactions (as parent spans). Built on System.Diagnostics.Metrics; zero-cost when nobody is listening. Learn more
  • JSON Schema validationShiny.DocumentDb.JsonSchema attaches a JSON Schema (draft 2020-12) to a document type and validates the exact JSON about to be persisted just before the write. options.MapJsonSchema<Customer>(schemaJson) needs no DI (works with a hand-built new DocumentStore(options)); a failure throws DocumentSchemaValidationException with field-level errors and rolls the write back. Enforces what the C# type can’t — maxLength, ranges, pattern, enum, format. Learn more
  • OData query endpointsShiny.DocumentDb.OData + Shiny.DocumentDb.AspNetCore.OData expose a document type as an OData v4 entity set: $filter/$orderby/$top/$skip/$count/$select translate onto the fluent query and run against any provider. Global query filters always apply underneath, and per-entity-set ODataQueryPolicy governance locks down public endpoints. Learn more
  • Offline-first syncShiny.DocumentDb.AppDataSync makes the store the local cache of an offline-first app that bidirectionally syncs to an HTTP backend via Shiny.Data.Sync. SyncDocumentStore(sync => sync.Sync<TodoItem>()) turns an ordinary document type into a two-way synced one — every local write is auto-enqueued to the outbox and every pulled server change is auto-applied back. Client-tier providers (SQLite, LiteDB, IndexedDB). Learn more
  • .NET Aspire integrationShiny.DocumentDb.Aspire.Hosting / .Client / .Orleans make the backend a deployment decision: builder.AddPostgresDocumentStore("orders").WithSeeder(...) in the AppHost picks the provider and gates seeding; the consuming service calls builder.AddDocumentStore("orders") for the keyed store wired with health checks + OpenTelemetry. Learn more
  1. Install the NuGet packages

    Install the core package plus your provider:

    Terminal window
    dotnet add package Shiny.DocumentDb.Sqlite

    Each provider package includes the core Shiny.DocumentDb package automatically.

    For dependency injection, also install the DI extensions package:

    Terminal window
    dotnet add package Shiny.DocumentDb.Extensions.DependencyInjection
  2. Register with dependency injection:

    using Shiny.DocumentDb;
    services.AddDocumentStore(opts =>
    {
    opts.DatabaseProvider = new SqliteDatabaseProvider("Data Source=mydata.db");
    });

    Just swap the provider for your database:

    opts.DatabaseProvider = new SqliteDatabaseProvider("Data Source=mydata.db");

    MongoDB uses its own options class — register the store directly with the DI container:

    builder.Services.AddSingleton(new MongoDbDocumentStoreOptions
    {
    ConnectionString = "mongodb://localhost:27017",
    DatabaseName = "mydb"
    });
    builder.Services.AddSingleton<IDocumentStore, MongoDbDocumentStore>();

    For multiple databases, register named stores using .NET keyed services:

    services.AddDocumentStore("users", opts =>
    {
    opts.DatabaseProvider = new SqliteDatabaseProvider("Data Source=users.db");
    });
    services.AddDocumentStore("analytics", opts =>
    {
    opts.DatabaseProvider = new PostgreSqlDatabaseProvider("Host=...");
    });

    Inject via [FromKeyedServices("name")] or resolve dynamically with IDocumentStoreProvider:

    public class MyService(
    [FromKeyedServices("users")] IDocumentStore userStore,
    [FromKeyedServices("analytics")] IDocumentStore analyticsStore) { }
    // Or dynamically:
    public class MyService(IDocumentStoreProvider stores)
    {
    void DoWork() => stores.GetStore("users").Insert(...);
    }

    For multi-tenant applications, two isolation strategies are available:

    // Shared-table: single database, automatic TenantId column filtering
    services.AddSingleton<ITenantResolver, MyTenantResolver>();
    services.AddDocumentStore(opts =>
    {
    opts.DatabaseProvider = new PostgreSqlDatabaseProvider("Host=...");
    }, multiTenant: true);
    // ...or a named/keyed shared-table store (resolve with [FromKeyedServices("orders")]):
    services.AddDocumentStore("orders", opts =>
    {
    opts.DatabaseProvider = new PostgreSqlDatabaseProvider("Host=...");
    }, multiTenant: true);
    // Tenant-per-database: separate database per tenant (scoped IDocumentStore)
    services.AddSingleton<ITenantResolver, MyTenantResolver>();
    services.AddMultiTenantDocumentStore(tenantId => new DocumentStoreOptions
    {
    DatabaseProvider = new SqliteDatabaseProvider($"Data Source={tenantId}.db")
    });

    Both require an ITenantResolver implementation:

    public class MyTenantResolver(IHttpContextAccessor http) : ITenantResolver
    {
    public string GetCurrentTenant()
    => http.HttpContext?.User.FindFirst("tenant_id")?.Value
    ?? throw new InvalidOperationException("No tenant context");
    }

    Or instantiate directly (no DI needed):

    // Quick setup (SQLite convenience class)
    var store = new SqliteDocumentStore("Data Source=mydata.db");
    // Full options
    var store = new SqliteDocumentStore(new DocumentStoreOptions
    {
    DatabaseProvider = new SqliteDatabaseProvider("Data Source=mydata.db")
    });
  3. Inject IDocumentStore and start using it:

    public class MyService(IDocumentStore store)
    {
    public async Task SaveUser(User user)
    {
    await store.Insert(user); // Id auto-generated for Guid/int/long; string Ids must be set
    }
    public async Task<User?> GetUser(string id)
    {
    return await store.Get<User>(id);
    }
    public async Task<IReadOnlyList<User>> GetActiveUsers()
    {
    return await store.Query<User>()
    .Where(u => u.IsActive)
    .OrderBy(u => u.Name)
    .ToList();
    }
    }
PropertyTypeDefaultDescription
DatabaseProviderIDatabaseProvider (required)The database provider to use (e.g. SqliteDatabaseProvider, SqlCipherDatabaseProvider, SqlServerDatabaseProvider, MySqlDatabaseProvider, PostgreSqlDatabaseProvider, DuckDbDatabaseProvider). LiteDB, CosmosDB, MongoDB, and IndexedDB use their own options classes.
TableNamestring"documents"Default table name for all document types not mapped via MapTypeToTable
TypeNameResolutionTypeNameResolutionShortNameHow type names are stored (ShortName or FullName)
JsonSerializerOptionsJsonSerializerOptions?nullJSON serialization settings. When a JsonSerializerContext is attached as the TypeInfoResolver, all methods auto-resolve type info from the context
UseReflectionFallbackbooltrueWhen false, throws InvalidOperationException if a type can’t be resolved from the configured TypeInfoResolver instead of falling back to reflection. Recommended for AOT deployments
LoggingAction<string>?nullCallback invoked with every SQL statement executed
TenantIdAccessorFunc<string>?nullWhen set, enables shared-table multi-tenancy. All queries are filtered by TenantId and all inserts include the TenantId value. A dedicated TenantId column and index are created automatically

By default all document types share a single table. Use MapTypeToTable to give a type its own dedicated table. Tables are lazily created on first use. Two types cannot map to the same custom table.

var store = new DocumentStore(new DocumentStoreOptions
{
DatabaseProvider = new SqliteDatabaseProvider("Data Source=mydata.db"),
TableName = "docs" // change the default table name (optional)
}
.MapTypeToTable<Order>("orders") // explicit table name
.MapTypeToTable<AuditLog>() // auto-derived table name "AuditLog"
// User stays in the default "docs" table
);

By default every document type must have a property named Id. Override that with a custom property using either MapTypeToTable<T>(...) (combined with a dedicated table) or MapIdProperty<T>(...) (the type stays in the default shared table). The two are independent — use either, both, or neither.

var store = new DocumentStore(new DocumentStoreOptions
{
DatabaseProvider = new SqliteDatabaseProvider("Data Source=mydata.db")
}
// Dedicated table + custom Id
.MapTypeToTable<Sensor>("sensors", s => s.DeviceKey) // Guid DeviceKey as Id
.MapTypeToTable<Tenant>("tenants", t => t.TenantCode) // string TenantCode as Id
// Default shared table + custom Id
.MapIdProperty<BlogPost>(p => p.Slug) // string Slug as Id
);

MapTypeToTable and MapIdProperty overloads

Section titled “MapTypeToTable and MapIdProperty overloads”
OverloadDescription
MapTypeToTable<T>()Auto-derive table name from type name
MapTypeToTable<T>(string tableName)Explicit table name
MapTypeToTable<T>(Expression<Func<T, object>> idProperty)Auto-derive table + custom Id
MapTypeToTable<T>(string tableName, Expression<Func<T, object>> idProperty)Explicit table + custom Id
MapIdProperty<T>(Expression<Func<T, object>> idProperty)Custom Id only — type stays in the default shared table
MapIdProperty<T>(string propertyName)AOT-safe string overload

All overloads return DocumentStoreOptions for fluent chaining. Duplicate table names throw InvalidOperationException.

services.AddDocumentStore(opts =>
{
opts.DatabaseProvider = new SqliteDatabaseProvider("Data Source=mydata.db");
opts.MapTypeToTable<User>();
opts.MapTypeToTable<Order>("orders");
opts.MapTypeToTable<Sensor>("sensors", s => s.DeviceKey);
});
claude plugin marketplace add shinyorg/skills
claude plugin install shiny-data@shiny
copilot plugin marketplace add https://github.com/shinyorg/skills
copilot plugin install shiny-data@shiny
View shiny-data Plugin