MongoDB Store
MongoDB store for document-oriented and horizontally-scalable Ledger deployments.
The store/mongo package implements Ledger's store.Store interface using the grove ORM with the MongoDB driver. Plans, subscriptions, invoices, and usage events are stored as documents, making it a natural fit for deployments that already run MongoDB.
Setup
import (
"github.com/xraph/grove"
"github.com/xraph/grove/drivers/mongodriver"
"github.com/xraph/ledger"
"github.com/xraph/ledger/store/mongo"
)
db, err := grove.Open(mongodriver.Open("mongodb://localhost:27017", "ledger"))
if err != nil {
log.Fatal(err)
}
s := mongo.New(db)
engine := ledger.New(s,
ledger.WithMeterConfig(100, 5*time.Second),
)
// Start runs migrations automatically
if err := engine.Start(ctx); err != nil {
log.Fatal(err)
}
defer engine.Stop()Migrations
Migrations run automatically when engine.Start() is called. They create collections with JSON Schema validation (auto-generated from Grove model structs) and apply indexes on all Ledger collections. For manual control:
if err := s.Migrate(ctx); err != nil {
log.Fatal(err)
}Implements store.Store
// Compile-time check
var _ store.Store = (*Store)(nil)Characteristics
| Aspect | Detail |
|---|---|
| Driver | grove ORM + mongodriver |
| Migrations | Grove migrations with JSON Schema validation + indexes |
| Transactions | MongoDB sessions (replica-set required for multi-doc txns) |
| Collections | ledger_plans, ledger_subscriptions, ledger_usage_events, ledger_entitlement_cache, ledger_invoices, ledger_coupons |
Grove Migrations
The store exports a Migrations group for use with Grove's migration orchestrator. This enables tracked, versioned migrations across all stores in your application:
import mongostore "github.com/xraph/ledger/store/mongo"
// mongostore.Migrations is a migrate.Group for the ledger mongo store.
// Register it with the grove migration orchestrator for coordinated migrations.When to use
- Document-oriented workloads where MongoDB is the primary data store.
- Horizontally-scaled environments requiring sharding.
- Teams already running MongoDB in their infrastructure.