Mongo Db

Description

MongoDB is used as a Document DB provider through the shared Flex document-store abstraction (IFlexDocumentStore). Generated code keeps your application code provider-agnostic: your queries/handlers talk to IFlexDocumentStore, and the provider wiring decides whether that’s MongoDB, Cosmos DB, Dynamo DB, etc.

Important Concepts

  • Query/Handler pattern: reads happen in .../Queries, writes happen in .../Handlers.

  • AppContext is mandatory: always call dto.GetAppContext() in queries/handlers (the templates mark it as “do not remove”).

  • Provider is hidden behind interfaces: your code depends on IFlexDocumentStore, not Mongo SDK types.

Configuration in DI (where to add)

Provider wiring is generated in your Infrastructure project (under a ...DataStoreProviders/Document/MongoDb folder). You typically do not register individual queries/handlers here — Flex generates and wires those.

If you are wiring Mongo manually, add the document-store provider registration where you configure infrastructure services (often in Program.cs or an Infrastructure DI module):

// Infrastructure (example)
services.AddFlexMongoDocumentStore<InvoiceDocument>(
    configuration,
    collectionName: "Invoices");

Where to put business registrations? Use your EndPoints “common configs” area (like OtherApplicationServicesConfig) for registering your own application services. The MongoDB provider itself is registered in Infrastructure.

appsettings.json

Examples (from the generated templates)

The generator uses the same shape for all Document DB providers; only the provider wiring changes.

Handler example (Create)

This follows the template in PostBusHandler/DocumentDataStore/DocumentStoreHandlerTemplate_Create.cs.

Query example (Get-by-id)

This follows the template in Query/DocumentDataStore/DocumentStoreQueryGetByIdTemplate.cs.

Query example (Simple list)

This follows the template in Query/DocumentDataStore/DocumentStoreQueryGetEnumerableTemplate.cs.

Provider-specific considerations

  • Replica sets: prefer replica-set aware connection strings for failover.

  • Indexing: define the “must have” indexes for your hot queries in configuration so deployments stay consistent.

  • Read preferences: align read preference with your consistency needs (primary vs preferred).

Last updated