Configuration Reference

Complete reference for all Morphium configuration options.

Overview

MorphiumConfig uses nested settings objects for different subsystems:

MorphiumConfig cfg = new MorphiumConfig();

// Access nested settings
cfg.connectionSettings().setDatabase("myapp");
cfg.clusterSettings().addHostToSeed("localhost", 27017);
cfg.driverSettings().setDriverName("PooledDriver");
// ... other settings

Connection Settings

Configure database connection parameters.

cfg.connectionSettings()
MethodDefaultDescription
setDatabase(String)requiredDatabase name to connect to
setConnectionTimeout(int)0Connection timeout in milliseconds
setMaxConnectionIdleTime(int)30000Max time connection can be idle (ms)
setMaxConnectionLifetime(int)600000Max connection lifetime (ms)
setMinConnections(int)1Minimum connections
setMaxConnections(int)250Maximum connections
setMaxWaitTime(int)2000Max wait time for connection from pool (ms)
setHeartbeatFrequency(int)1000Heartbeat frequency in milliseconds
setRetriesOnNetworkError(int)1Number of retries on network error
setSleepBetweenNetworkErrorRetries(int)1000Sleep between network error retries (ms)
setUseSSL(boolean)falseEnable SSL/TLS connections
setSslContext(SSLContext)nullCustom SSL context
setSslInvalidHostNameAllowed(boolean)falseAllow invalid host names (self-signed certs)

Cluster Settings

Configure MongoDB cluster/replica set connection.

cfg.clusterSettings()
MethodDefaultDescription
addHostToSeed(String, int)requiredAdd host:port to seed list
setRequiredReplicaSetName(String)nullReplica set name (auto-detected if null)
setHeartbeatFrequency(int)0Heartbeat frequency in milliseconds
setReplicaset(boolean)trueEnable replica set monitoring
setReplicaSetMonitoringTimeout(int)5000Monitoring timeout (ms)

Example

// Single host
cfg.clusterSettings().addHostToSeed("localhost", 27017);

// Replica set
cfg.clusterSettings().addHostToSeed("mongo1", 27017);
cfg.clusterSettings().addHostToSeed("mongo2", 27017);
cfg.clusterSettings().addHostToSeed("mongo3", 27017);
cfg.clusterSettings().setRequiredReplicaSetName("myReplicaSet");

⚠️ IPv6 Limitation: The current hostname normalization assumes IPv4 addresses or DNS hostnames. IPv6 addresses (e.g., [2001:db8::1]:27017) are not fully supported and may cause connection pool issues. Use DNS hostnames instead of raw IPv6 addresses when configuring MongoDB connections.

Driver Settings

Configure the MongoDB driver implementation.

cfg.driverSettings()
MethodDefaultDescription
setDriverName(String)"PooledDriver"Driver implementation to use
setIdleSleepTime(int)20Sleep time between idle checks (ms)
setSharedConnectionPool(boolean)falseShare driver/connection pool across Morphium instances with same hosts+database
setInMemorySharedDatabases(boolean)falseShare InMemoryDriver instance across Morphium instances with same database
setServerSelectionTimeout(int)30000Server selection timeout (ms)
setHeartbeatFrequency(int)1000Heartbeat frequency (ms)
setRetryReads(boolean)falseRetry read operations
setRetryWrites(boolean)falseRetry write operations
setLocalThreshold(int)15Local threshold for server selection (ms)
setMaxConnectionIdleTime(int)30000Max connection idle time (ms)
setMaxConnectionLifeTime(int)600000Max connection lifetime (ms)
setCursorBatchSize(int)1000Default batch size for cursors
setChangeStreamBatchSize(int)100getMore batch size for change stream cursors (messaging, watch). See note below.

Change Stream Batch Size

setChangeStreamBatchSize(int) controls the getMore batch size of change stream cursors (used by messaging and watch()). It defaults to 100.

A batch size of 1 delivers exactly one event per getMore round-trip, capping stream throughput at roughly one event per network round-trip. On localhost this is unnoticeable, but over a high-latency link (e.g. an SSH/SOCKS tunnel with tens of milliseconds RTT) a busy stream cannot keep up: it drains its backlog at only ~1/RTT events per second and falls behind, delivering events — including messaging answers awaited by sendAndAwaitAnswers() — up to tens of seconds late, until traffic drops and the cursor catches up. A larger batch adds no latency at low traffic (the cursor returns as soon as the first event is available) but lets a single round-trip drain many backlogged events. The effective batch is still bounded by MongoDB's ~16MB per-reply limit regardless of the configured count.

The value can be overridden per monitor via ChangeStreamMonitor.setBatchSize(int) before start(); an unset monitor inherits driverSettings().getChangeStreamBatchSize().

// raise for high-latency links / busy streams
cfg.driverSettings().setChangeStreamBatchSize(500);

Available Drivers

  • PooledDriver (default): Connection pooling with replica set support
  • SingleMongoConnectDriver: Single connection driver
  • InMemDriver: In-memory driver for testing

Authentication Settings

Configure MongoDB authentication.

cfg.authSettings()
MethodDefaultDescription
setMongoLogin(String)nullMongoDB username
setMongoPassword(String)nullMongoDB password
setMongoAdminUser(String)nullAdmin user for replica set operations
setMongoAdminPwd(String)nullAdmin password for replica set operations
setAuthMechanism(String)nullAuth mechanism: "MONGODB-X509" for certificate-based auth (requires SSL)

Example — password authentication

cfg.authSettings().setMongoLogin("appuser");
cfg.authSettings().setMongoPassword("secret123");

// Admin user for replica set status (optional)
cfg.authSettings().setMongoAdminUser("admin");
cfg.authSettings().setMongoAdminPwd("adminsecret");

Example — MONGODB-X509 (certificate-based, no password)

// SSL + mTLS must be configured (see docs/ssl-tls.md)
cfg.authSettings().setAuthMechanism("MONGODB-X509");
// no setMongoLogin / setMongoPassword needed

Cache Settings

Configure the global caching behavior.

cfg.cacheSettings()
MethodDefaultDescription
setGlobalCacheValidTime(int)5000Global cache TTL in milliseconds
setHousekeepingTimeout(int)5000Cache housekeeping interval (ms)

Messaging Settings

Configure the messaging system.

cfg.messagingSettings()
MethodDefaultDescription
setMessageQueueName(String)"msg"Base name for message collections
setMessagingWindowSize(int)100Number of messages to process per batch
setMessagingMultithreadded(boolean)trueEnable multithreaded message processing
setUseChangeStream(boolean)trueUse MongoDB Change Streams for messaging
setMessagingPollPause(int)250Pause between message polls (ms)
setProcessMultiple(boolean)trueProcess multiple messages if available
setAutoAnswer(boolean)falseAutomatically answer messages
setMessagingImplementation(String)"StandardMessaging"Implementation class alias
setThreadPoolMessagingCoreSize(int)0Thread pool core size
setThreadPoolMessagingMaxSize(int)100Thread pool max size
setThreadPoolMessagingKeepAliveTime(long)2000Thread keep-alive time (ms)

Thread Pool Settings

Configure async operation thread pools.

cfg.threadPoolSettings()
MethodDefaultDescription
setThreadPoolAsyncOpCoreSize(int)1Core thread pool size
setThreadPoolAsyncOpMaxSize(int)1000Maximum thread pool size
setThreadPoolAsyncOpKeepAliveTime(long)1000Thread keep-alive time (ms)

Writer Settings

Configure write operation behavior.

cfg.writerSettings()
MethodDefaultDescription
setWriteBufferTime(int)1000Buffer flush timeout (ms)
setWriteBufferTimeGranularity(int)100Time granularity for buffer checks (ms)
setMaximumRetriesWriter(int)10Max retries for direct writer
setMaximumRetriesBufferedWriter(int)10Max retries for buffered writer
setMaximumRetriesAsyncWriter(int)10Max retries for async writer
setRetryWaitTimeWriter(int)200Wait between writer retries (ms)
setRetryWaitTimeBufferedWriter(int)200Wait between buffered writer retries (ms)
setRetryWaitTimeAsyncWriter(int)200Wait between async writer retries (ms)
setThreadConnectionMultiplier(int)5Multiplier for connections per thread

Object Mapping Settings

Configure object mapping behavior.

cfg.objectMappingSettings()
MethodDefaultDescription
setCheckForNew(boolean)trueCheck if entity is new before store
setAutoValues(boolean)trueEnable automatic value generation (@LastChange, etc.)
setObjectSerializationEnabled(boolean)trueEnable object serialization
setCamelCaseConversionEnabled(boolean)trueConvert camelCase to snake_case in MongoDB
setWarnOnNoEntitySerialization(boolean)falseWarn if no entity serialization is available
setUseBsonDateForJavaTime(boolean)falseStore Instant, LocalDate, LocalTime and LocalDateTime as native BSON Date instead of Morphium's legacy formats. Mapper path only, see below
setTranslateAggregationFieldNames(boolean)falseTranslate Java property names in aggregation stages to stored field names (overridable per aggregator)
objectMappingSettings().setEnumType(EnumType)STRINGHow an enum is stored in a field without @Enumerated: STRING (the name of the constant) or ORDINAL (its position, so a sort and a range query follow the order of the constants). Existing documents are not rewritten, reading takes both forms. The ordinal changes when a constant is inserted or moved: add new constants at the end. See "Enums" below
setTranslateUpdateFieldNames(boolean)trueTranslate the field names in the operator maps of Query.findOneAndUpdate ($set, $unset, $rename, ... incl. dotted keys through single embedded fields) to the names the fields are stored under. Kill switch: false writes the keys exactly as given. Overridable per query with Query.setTranslateUpdateFieldNames(Boolean). Aliases, unknown, positional and $-prefixed keys are never translated
setStrictEmbeddedNaming(boolean)falseAn @Embedded class with the default translateCamelCase=true inside a class with translateCamelCase=false is stored in snake_case while its owner keeps its names. The mapper logs a warning once per entity class that names owner, field and embedded class; with true it throws an IllegalStateException at the first use of the entity instead. The stored data is the same either way. Set translateCamelCase=false on the embedded class if camelCase keys are intended

Enums

An enum is stored by the name of its constant. Two ways to store the ordinal instead:

  • @Enumerated(EnumType.ORDINAL) on a field (also for a List or Set of enums and the values of a Map), like @Enumerated of JPA. @Enumerated(EnumType.STRING) keeps a field on the name when the setting says otherwise.
  • objectMappingSettings().setEnumType(EnumType.ORDINAL) (morphium.enum-type in Spring, quarkus.morphium.enum-type in Quarkus) for all fields without the annotation.

As an ordinal an enum sorts and compares in the order of its constants (sort, gt, lte, BETWEEN); stored by name it sorts alphabetically. Queries, updates (modify(), set(), push(), JDQL UPDATE) and the derived and JDQL queries of the Jakarta Data module write the form that the field stores. Reading accepts both forms whatever is configured, so the setting can be changed without a migration, but the documents that were written before keep their form, and a query finds only the form it writes: change the setting together with a migration of the data. The keys of a map are always names.

useBsonDateForJavaTime: where it applies

The flag is evaluated by the java.time custom mappers, so it applies wherever a value passes through the object mapper:

  • entity persistence (store()),
  • filters built with the type-safe query API (query.f("field").lt(instant)),
  • the update APIs (set(), push(), addToSet() and friends, Query#findOneAndUpdate(Map) and the update builder Query#modify()).

It does not apply to maps you build yourself. Those reach BsonEncoder without passing a mapper, and the encoder writes java.time values in the legacy format regardless of the flag (Instant and LocalDateTime as sub-documents, LocalDate/LocalTime as longs). This affects:

  • query and update maps passed to driver commands directly, e.g. FindAndModifyMongoCommand#setQuery / #setUpdate (the update map of Query#findOneAndUpdate(Map) is mapped),
  • a filter set via Query#rawQuery(Map).

A $lt/$lte against such a value compares a sub-document, not a date, and does not match fields written as native dates. Put a java.util.Date into the map instead:

var now = Instant.now();
var query = Map.<String, Object>of("expiresAt", Map.of("$lte", Date.from(now)));
var update = Map.<String, Object>of("$set", Map.of("expiresAt", Date.from(now.plus(leaseDuration))));

BsonEncoder always writes a Date as BSON type 0x09, and every java.time mapper reads a Date back, so the entity field can stay an Instant. Precision is milliseconds, the same as with the flag. morphium.getMapper().marshallIfCustomMapped(value) also produces a Date, but only while the flag is on; with the flag off it produces the legacy shape again.

Error Handling Settings

Configure retry and error handling behavior.

cfg.connectionSettings()
MethodDefaultDescription
setRetriesOnNetworkError(int)5Number of retries on network errors
setSleepBetweenErrorRetries(int)100Sleep between error retries (ms)

Configuration Sources

Morphium supports multiple configuration sources:

1. Programmatic Configuration

MorphiumConfig cfg = new MorphiumConfig();
cfg.connectionSettings().setDatabase("myapp");
// ... other settings

2. Properties File

Properties props = new Properties();
props.load(new FileInputStream("morphium.properties"));
MorphiumConfig cfg = new MorphiumConfig(props);

Example morphium.properties:

database=myapp
hosts=mongo1:27017,mongo2:27017,mongo3:27017
replica_set_name=myReplicaSet
driver_name=PooledDriver
max_connections_per_host=50
mongo_login=appuser
mongo_password=secret123

3. JSON Configuration

String json = Files.readString(Paths.get("morphium-config.json"));
MorphiumConfig cfg = MorphiumConfig.createFromJson(json);

Example JSON:

{
  "database": "myapp",
  "hosts": ["mongo1:27017", "mongo2:27017", "mongo3:27017"],
  "replicaSetName": "myReplicaSet",
  "driverName": "PooledDriver",
  "maxConnectionsPerHost": 50,
  "mongoLogin": "appuser",
  "mongoPassword": "secret123"
}

Environment-Specific Configurations

Development

MorphiumConfig cfg = new MorphiumConfig();
cfg.connectionSettings().setDatabase("myapp_dev");
cfg.clusterSettings().addHostToSeed("localhost", 27017);
cfg.driverSettings().setDriverName("PooledDriver");
cfg.connectionSettings().setMaxConnectionsPerHost(10); // Lower for dev

Testing

MorphiumConfig cfg = new MorphiumConfig();
cfg.connectionSettings().setDatabase("myapp_test");
cfg.driverSettings().setDriverName("InMemDriver"); // In-memory for tests

Production

MorphiumConfig cfg = new MorphiumConfig();
cfg.connectionSettings().setDatabase("myapp_prod");
cfg.clusterSettings().addHostToSeed("mongo1", 27017);
cfg.clusterSettings().addHostToSeed("mongo2", 27017);
cfg.clusterSettings().addHostToSeed("mongo3", 27017);
cfg.connectionSettings().setMaxConnectionsPerHost(100);
cfg.connectionSettings().setMaxWaitTime(10000);
cfg.authSettings().setMongoLogin("produser");
cfg.authSettings().setMongoPassword(System.getenv("MONGO_PASSWORD"));

Common Configuration Patterns

High Throughput

cfg.connectionSettings().setMaxConnectionsPerHost(200);
cfg.connectionSettings().setMaxWaitTime(5000);
cfg.messagingSettings().setMessagingWindowSize(500);
cfg.messagingSettings().setMessagingMultithreadded(true);

Low Latency

cfg.connectionSettings().setMinConnectionsPerHost(20);
cfg.connectionSettings().setConnectionTimeout(500);
cfg.connectionSettings().setMaxWaitTime(1000);
cfg.clusterSettings().setHeartbeatFrequency(1000);

High Availability

cfg.connectionSettings().setRetriesOnNetworkError(10);
cfg.connectionSettings().setSleepBetweenErrorRetries(200);
cfg.clusterSettings().setServerSelectionTimeout(5000);
cfg.connectionSettings().setMaxConnectionIdleTime(300000);
← Back to Documentation Hub