Aller au contenu
Français

MongoDB

Ce contenu n’est pas encore disponible dans votre langue.

The MongoDB backend provides all four persistence components against a single MongoDB deployment, via the mongodb driver:

  • MongoJournal — the event journal for PersistentActors.
  • MongoSnapshotStore — snapshots to bound recovery.
  • MongoDurableStateStore — key-value durable state for DurableStateActors.
  • MongoQuery — an indexed currentEventsByTag, which the relational backends do not have.

It is the first document-store backend, and it needs no replica set: see No transactions required.

mongodb is an optional peer dependency. Version 6 and version 7 are both supported:

Terminal window
bun add mongodb@^7 # or mongodb@^6

The framework imports the driver only when a MongoDB store opens — at startup, or on first use when the boot-time open is turned off — so it stays out of your bundle until you opt in.

Register all three stores through the plugins slot of the system’s options and select them in its configuration. Set the connection once on the composite and all three components inherit it:

import {
ActorSystem,
ActorSystemOptions,
} from 'actor-ts';
import {
MongoDurableStateStoreOptions,
MongoJournalOptions,
MongoSnapshotStoreOptions,
RegisterMongoPluginsOptions,
registerMongoPlugins,
} from 'actor-ts/persistence';
const mongoSnapshotStoreOptions = MongoSnapshotStoreOptions.create()
.withKeepN(3);
const registerOptions = RegisterMongoPluginsOptions.create()
.withUrl('mongodb://user:pass@localhost:27017')
.withDatabaseName('app')
.withJournal(MongoJournalOptions.create() /* .withEventsCollection(...) */)
.withSnapshotStore(mongoSnapshotStoreOptions)
.withDurableStateStore(MongoDurableStateStoreOptions.create() /* .withCollection(...) */);
const systemOptions = ActorSystemOptions.create()
// Select the MongoDB plugins for all three stores.
.withConfig({
'actor-ts': {
persistence: {
journal: { plugin: 'actor-ts.persistence.journal.mongodb' },
'snapshot-store': { plugin: 'actor-ts.persistence.snapshot-store.mongodb' },
'durable-state': { plugin: 'actor-ts.persistence.durable-state.mongodb' },
},
},
})
.withPersistence({ plugins: [(persistence) => registerMongoPlugins(persistence, registerOptions)] });
const system = ActorSystem.create('my-app', systemOptions);

The plug-in runs inside ActorSystem.create and registers all three stores — the journal, the snapshot store and, since #872, the durable-state store, which the durable-state.plugin key now selects like the other two — so the ones the configuration selects open as part of the startup: a deployment the node cannot reach fails the startup rather than the first persisted message — see opening the stores at startup. That holds however a store is set up, as long as the boot-time open is on, the default. Each open sends one { ping: 1 } before it creates any index — with auto-create-indexes off as well, over a client you handed over, and for the durable-state store, which creates no index at all — and a refused ping fails the open with an error naming the store. The ping needs no privilege, reads nothing and creates nothing. It goes through the database handle’s command, which the driver’s handle always has; a stand-in handed over without one is not pinged. It holds for these stores, not for every axis: an object-storage snapshot or durable-state store selected beside them, or a store of your own without start(), has nothing to open ahead of time and fails its first operation instead. The returned durableStateStore still works and still yields the same instance; it is simply built when it is first asked for rather than at registration, so a caller who prefers to hand it to DurableStateActor in code can carry on doing exactly that — a plug-in keeps it by assigning the result, (persistence) => { mongo = registerMongoPlugins(persistence, registerOptions); }. A store wired by hand is not a selected one, though, so it opens on first use rather than with the startup.

The plugin id is the config section, so the block named after the id is the block that plugin reads (#872). Everything except the live objects can come from application.conf, which means registerMongoPlugins(persistence) needs no options at all:

import { ActorSystem, ActorSystemOptions } from 'actor-ts';
import { registerMongoPlugins } from 'actor-ts/persistence';
const systemOptions = ActorSystemOptions.create().withPersistence({
plugins: [(persistence) => registerMongoPlugins(persistence)],
});
const system = ActorSystem.create('my-app', systemOptions);
actor-ts.persistence {
journal { plugin = "actor-ts.persistence.journal.mongodb" }
snapshot-store { plugin = "actor-ts.persistence.snapshot-store.mongodb" }
durable-state { plugin = "actor-ts.persistence.durable-state.mongodb" }
journal.mongodb { url = ${?MONGO_URL}, database-name = "app", events-collection = "events" }
snapshot-store.mongodb { url = ${?MONGO_URL}, database-name = "app", keep-n = 5 }
durable-state.mongodb { url = ${?MONGO_URL}, database-name = "app", collection = "durable_state" }
}

The leaves say collection, not table, and the switch is auto-create-indexes rather than auto-create-tables — the block speaks Mongo’s vocabulary, because a leaf named after another backend’s is a leaf you have to translate. The connection is repeated under each of the three roots rather than hoisted: a plugin id is its config section and the three axes are selected independently, so they may legitimately name different deployments. Write it once and substitute if they do not.

Options passed to registerMongoPlugins still win, field by field, and a field you leave unset falls through to the block rather than blanking it — so a shared client in code and the collection names in HOCON is a normal mix. A pre-built client and a serializer have no leaf at all: they are live objects, and a config file cannot express one. Neither does clientOptions — the driver’s whole option surface, which stays code-only.

What you do tune on the client has typed leaves (#1490), each a comment in the reference configuration so that leaving it out keeps the driver’s own default:

actor-ts.persistence.journal.mongodb {
url = ${?MONGO_URL}
max-pool-size = 50 # the driver's maxPoolSize (default 100)
min-pool-size = 5 # minPoolSize (default 0)
server-selection-timeout = 10s # serverSelectionTimeoutMS (default 30s)
connect-timeout = 5s # connectTimeoutMS (default 30s)
ca-file = "/etc/ssl/mongo-ca.pem" # read when the client opens, handed over as ca
}

Each reaches the driver only when set, under the driver’s own name. The store checks them when it is built: a pool size or timeout that is not a positive whole number (a minimum pool size of 0, the default, is fine), a minimum above the maximum, or a timeout longer than a timer can hold, is refused with an OptionsError. So is a leaf beside the same option in clientOptions or in the url’s query (max-pool-size beside maxPoolSize=20, say), naming both: the driver reads all three case-insensitively, keeps the object’s value and drops the url’s without a word, so the store asks you to set it in one place instead. ca-file is a path the framework reads, never the certificate itself; a file it cannot read fails the store’s open — the startup, or its first use when the boot-time open is turned off — naming the leaf and the path.

A url that switches TLS verification off is refused. tlsInsecure, tlsAllowInvalidCertificates or tlsAllowInvalidHostnames set to anything but false makes the reader throw a ConfigError naming the leaf and the switch, in any letter case of the key and whether the url is written out or substituted from ${?MONGO_URL}. The refusal is strict about the file: the block’s url is refused even when registerMongoPlugins is given a url or a client of its own. Only HOCON is inspected — the same string passed to withUrl(...), and clientOptions, are your code’s decision. A private CA needs no code at all: name its file with the block’s ca-file leaf, which the framework reads and hands over with TLS on, or with tls=true&tlsCAFile=<CA file> in the url, which the driver reads itself. One or the other: the driver reads tlsCAFile only when no CA was handed over, so ca-file beside it is refused rather than one of the two quietly dropped. tls=false is plaintext rather than unverified TLS and stays allowed — though not beside ca-file, which it would leave unused.

With ca-file set, code is held to it as well. The store refuses the leaf when it is built, with an OptionsError naming both sides, beside a ca or a tlsCAFile in clientOptions; beside a tls, ssl, tlsInsecure or tlsAllowInvalidCertificates there that would leave the CA unused; beside a rejectUnauthorized of false, in any letter case of the key, which is the switch tlsInsecure sets; and beside a secureContext, which brings a trust store of its own that is used in place of the CA. A pre-built client beside ca-file is refused too: it was configured where it was built and never reads the leaf, so give that client its CA, or pass url instead. The reasoning is on TLS everywhere.

A MongoClient is a connection pool in its own right, so passing one is the efficient shape when all components target the same deployment:

import { MongoClient } from 'mongodb';
const client = new MongoClient('mongodb://localhost:27017');
await client.connect();
const registerMongoPluginsOptions = RegisterMongoPluginsOptions.create()
.withClient(client)
.withDatabaseName('app');
const systemOptions = ActorSystemOptions.create().withPersistence({
plugins: [(persistence) => registerMongoPlugins(persistence, registerMongoPluginsOptions)],
});

A shared client is caller-owned: no store closes it, so close it yourself during shutdown. Pass url instead and each store builds its own client and closes it on close(). Each store still reaches the deployment when it opens, through the shared client — its ping goes that way — and none of them takes ca-file beside it: configure the client’s TLS where you build it.

  • MongoDB is already your database. The largest driver in the ecosystem, and the one many teams already operate.
  • You want indexed tag queries. Only MongoDB, SQLite/libSQL and Cassandra push currentEventsByTag down to storage; the relational backends poll.
  • You want a single deployment for events and read models. Projections can write their views into the same database.
type MongoConnection = {
url?: string; // mongodb:// or mongodb+srv://
databaseName?: string; // default 'actor_ts'
clientOptions?: Record<string, unknown>; // extra MongoClient options — the code-only long tail
client?: MongoClientLike; // pre-built / shared client
maxPoolSize?: number; // maxPoolSize, default 100 (max-pool-size)
minPoolSize?: number; // minPoolSize, default 0 (min-pool-size)
serverSelectionTimeoutMs?: number; // serverSelectionTimeoutMS, 30 000 (server-selection-timeout)
connectTimeoutMs?: number; // connectTimeoutMS, 30 000 (connect-timeout)
caFile?: string; // PEM file read into ca, with tls on (ca-file)
};
interface MongoJournalOptions extends MongoConnection {
eventsCollection?: string; // default 'events'; its mark collection is '<it>_meta'
autoCreateIndexes?: boolean; // default true
}
interface MongoSnapshotStoreOptions extends MongoConnection {
snapshotsCollection?: string; // default 'snapshots'
keepN?: number; // keep newest N per pid; default 3, <=0 keeps all
autoCreateIndexes?: boolean;
}
interface MongoDurableStateStoreOptions extends MongoConnection {
collection?: string; // default 'durable_state'
}

Options are validated when the store is constructed, so a bad URL scheme or a database name MongoDB would refuse (one containing /, \, ., " or a space) fails at wiring time rather than on the first write. A replica-set seed list without SRV, such as mongodb://h1:27017,h2:27017,h3:27017/app?replicaSet=rs, is accepted as the driver accepts it; a mongodb+srv:// url, by contrast, names exactly one host and no port, because DNS supplies the members.

CollectionShapeIndex
events{ persistenceId, sequenceNr, payload, tags?, timestamp }unique (persistenceId, sequenceNr); (tags, timestamp)
events_meta{ _id: persistenceId, deletedTo }_id
snapshots{ persistenceId, sequenceNr, payload, timestamp }unique (persistenceId, sequenceNr)
durable_state{ _id: persistenceId, revision, payload, timestamp }_id
  • Journal append reads the current head and then inserts. The unique compound index rejects a racing writer with server error 11000, which is translated into JournalConcurrencyError — the same two-layer scheme as the SQL backends (a head check for the ordinary case, a conditional write for the race), with error 11000 in the role of SQLSTATE 23505.
  • Durable-state CAS puts the revision in the filter: updateOne({ _id, revision: expected }, …). A mismatch matches nothing, so matchedCount === 0 means the stored revision diverged. A create is insertOne, where _id rejects a duplicate.
  • The compaction mark is monotonic via $max, which writes only when the new value is greater — exactly what GREATEST does in the SQL dialects.

MongoDB multi-document transactions need a replica set, and this backend deliberately does not use them, so it works on a standalone mongod.

That is sound rather than lucky. Appends are contiguous from the head, so two writers that agree on the head both try the same first sequence number: the loser’s insertMany fails on its very first document, and ordered: true stops the batch there, so it writes nothing. A partial append is not reachable through contention — which is the only thing a transaction would have bought.

MongoQuery gives currentEventsByTag an indexed path. Because tags is an array, MongoDB indexes it as a multikey index — one entry per tag per event — so a query on one tag plus a timestamp lower bound walks a contiguous range instead of scanning:

import { MongoQuery, offsetStart } from 'actor-ts/persistence';
const query = new MongoQuery(journal);
const tagged = await query.currentEventsByTag({ all: ['ledger'], not: ['audit'] }, offsetStart);

The server pre-filters on one tag; all past the first tag, cross-tag any and not are refined in memory, exactly as in the SQLite and Cassandra paths. A filter with only not has nothing to pre-filter on and falls back to the journal-walking scan.

  • PostgreSQL — the relational counterpart, with transactional multi-event appends.
  • Cassandra journal — the other distributed store with an indexed tag path.
  • Durable state — the state-oriented alternative to event sourcing.
  • Snapshots — bound the recovery scan.