The smallmind-mongodb parent module collects two publishable artifacts
that sit on top of the stock
MongoDB Java driver
(mongodb-driver-sync, mongodb-driver-core, bson):
-
mongodb-utility— five small classes and a singleMongoAcknowledgmentenum that turn the driver’s builder-heavy configuration surface (MongoClientSettings.builder(), cluster settings, pool settings, SSL context, credential assembly) into a handful of SpringFactoryBeanimplementations. A runningMongoClientcomes out the other end as a managed singleton with adestroy()that closes the client during context shutdown. -
mongodb-throng— a small, annotation-driven object/document mapper built against the driver’s ownCodec/CodecRegistryinfrastructure. It vends a singleThrongClientwhose CRUD surface (count,find,findOne,insert,update,delete) is statically typed over@Entity-annotated Java classes and whose query, projection, sort, and update DSLs are thin fluent wrappers aroundcom.mongodb.client.model.Filters,Projections,Sorts, andUpdates.
The two modules are independent — mongodb-throng does not depend on
mongodb-utility, and an application can adopt either one alone — but
the common deployment shape is to use mongodb-utility to construct
the driver MongoClient and then hand that client to a ThrongClient
together with the list of @Entity classes it should recognize.
The MongoDB Java driver is a complete, general-purpose API. However, many clients of that service will end up writing the same glue:
-
Walk a property file or Spring XML of broker hosts, convert them into
ServerAddressinstances, and feed the resulting array toClusterSettings.Builder#hosts. For anything more than a single mongo instance, produce that array by hand. -
Build a
MongoClientSettingsby chaining a half-dozenapplyToClusterSettings/applyToSocketSettings/applyToConnectionPoolSettings/applyToSslSettingslambdas, each of which mutates a separate builder. Remember which knobs belong to which builder. Remember thatWriteConcernattaches to the outer builder, not the cluster one. -
Carry a plaintext password into a
MongoCredentialwithout leaving aStringreference on the heap longer than necessary. -
Close the
MongoClientduring application shutdown so connection pools drain cleanly. -
Adopt a convention for turning Java classes into BSON documents — the driver vends a
PojoCodecProviderbut leaves decisions about id handling, polymorphism, embedded documents, lifecycle callbacks, and index creation to each project. -
Resolve indexes separately from mapping — read an annotation or configuration file, build a
NewIndex, callcreateIndexes(List<IndexModel>), and try to keep the two sides in sync when a schema evolves. -
Write the dozens of lines of
com.mongodb.client.model.Filtersandcom.mongodb.client.model.Updatesincantations that every typed query requires.
smallmind-mongodb assembles (1)–(4) once as mongodb-utility, and
(5)–(7) once as mongodb-throng. A caller that needs a working,
authenticated, pool-tuned MongoClient plus typed CRUD over its own
annotated entities writes this:
MongoClient mongoClient = /* from MongoClientFactoryBean */;
ThrongClient throng = new ThrongClient(
mongoClient,
"orders-db",
new ThrongOptions(false, true, true),
Order.class, OrderLine.class);
List<Order> open = throng.find(Order.class,
Query.with().filter(Filter.where("status").eq("OPEN"))
.sort(Sort.on().desc("placedAt"))
.limit(50))
.asList();…and never touches MongoClientSettings.builder, PojoCodecProvider,
IndexModel, or com.mongodb.client.model.Filters directly.
-
mongodb-utilityturns Spring XML into aMongoClient:-
models the cluster as
ServerAddress[]produced by a pattern/spread pair (mongo#.internal:27017+1-3); -
builds a single
MongoCredentialfor SCRAM-SHA-1 authentication; -
assembles a
MongoClientSettingsfrom 20+ nullable properties, applying each non-null value to the correct sub-builder and leaving the driver’s defaults where nothing is set; -
constructs and tears down the
MongoClientas a Spring-managed singleton; -
canonicalizes the five most common write-concern levels as an enum (
MongoAcknowledgment) and producesWriteConcerninstances with or without journaling via a non-singletonFactoryBean(MongoWriteConcern).
-
-
mongodb-throngturns annotated Java classes into typed CRUD:-
discovers mapping from five class-level and field-level annotations (
@Entity,@Embedded,@Id,@Property,@Codec) plus a polymorphism declaration (@Polymorphic); -
wires BSON codecs against the driver’s own
CodecRegistry— so every value passed into a filter or update still goes through the registered chain; -
supports entity lifecycle callbacks (
@PrePersist,@PostPersist,@PreLoad,@PostLoad) with strict rules about which arestatic, which take aBsonDocument, and which are for@Entityclasses only; -
discovers index declarations (
@Indexed,@Index,@Indexes,@AllIndexes) on the entity and applies them onThrongClientconstruction whencreateIndexesis on; -
vends fluent builders for filters (
Filter), updates (Updates), projections (Projections), and sorts (Sort), and composes them with paging and batch-size settings throughQuery; -
exposes results as a lazy
ThrongIterable<T>that decodes eachThrongDocumentinto a typed entity on demand, firing lifecycle callbacks as it goes.
-
-
It does not wrap
MongoClientorMongoCollection.ThrongClientis a single, non-transactional façade over aMongoDatabase; applications that need transactions or change streams should use the driverMongoClientdirectly and keepThrongClientfor CRUD and aggregation. -
It does not own the
MongoClientlifecycle from insideThrongClient. TheMongoClientpassed in is owned by the caller (typicallyMongoClientFactoryBean’s `destroy()). -
It supplies a small aggregation DSL (
Pipeline) covering the common pipeline stages ($match,$sort,$project,$skip,$limit,$count,$unwind,$lookup,$group) plus a raw-stage escape hatch. Anything else ($facet,$bucket,$graphLookup, change streams, transactions) is the driver’s job, reached through the rawMongoClient. -
It does not offer a reactive or async surface. Both modules target the synchronous driver.
-
It does not ship connection-string parsing (
MongoClientURI/ConnectionString). Theutilitymodule builds aMongoClientSettingsfrom typed components instead. -
It does not support entity-level polymorphism.
@Polymorphicis usable on@Embeddedclasses only; an@Entitywith@Polymorphicfails mapping.
If you are new to the module, read in this order:
If you know the driver and need a fast entry point:
If you are diagnosing a failure:
| Artifact | Module name | Role |
|---|---|---|
|
|
Spring |
|
|
Annotation-driven object/document mapper over the sync driver.
Exposes |
A few ideas recur throughout the module and are worth naming up front.
- Server pattern and spread
-
The mechanism
MongoServerFactoryBeanuses to turn one template into aServerAddress[]. Ain the pattern is replaced by each value produced byorg.smallmind.nutsnbolts.util.Spread.calculate(serverSpread).mongo.internal:27017with spread1-3yieldsmongo1.internal:27017,mongo2.internal:27017,mongo3.internal:27017. With no#, the pattern is parsed as a single host (with an explicit:portor the driver’s default27017). - Acknowledgment level
-
MongoAcknowledgmentis a closed enum of five write-concern choices:ZERO(unacknowledged, not journable),ONE,TWO,THREE, andMAJORITY(all journable). It exists so the Spring XML can use a simple enum literal rather than anorg.springframework.util.PropertiesUtil-style constant reference againstcom.mongodb.WriteConcern.MongoWriteConcernconsumes an acknowledgment plus ajournaledflag and emits a concreteWriteConcern— callingwithJournal(true)only when the chosen level is journable. - Codec registry composition
-
ThrongClientbuilds a singleCodecRegistryout of three pieces, in this order: (1) theThrongDocumentCodecfor rawThrongDocumentpass-through; (2) the embedded codecs it discovered while scanning@Embeddedclasses; (3) the database’s own registry wrapped with anArrayCodecProviderthat handles Java array fields. Every filter, update, or value written through the client goes through this merged registry. - Entity vs. embedded
-
An
@Entityis a top-level document that maps to a MongoDB collection. It has exactly one@Idfield, may declare lifecycle callbacks, and may declare indexes. An@Embeddedclass is a nested object with no collection of its own. It may not declare lifecycle callbacks; it may declare@Polymorphicto be discriminated across multiple subtypes; and its indexes, if any, must be declared on the parent entity. - Lazy decoding
-
ThrongIterable<T>wraps the driver’sFindIterable<ThrongDocument>and decodes each result into a typed entity only when the caller advances the iterator.asList()forces the full decode; iterator traversal decodes one document at a time. Lifecycle callbacks (@PreLoad/@PostLoad) fire at decode time, not at query time. - Filter state machine
-
A
Filterbuilt byFilter.where(field)is incomplete until a comparison method (eq,gt,in,regex, etc.) applies a condition. CallingtoBsonDocumenton an incomplete filter throwsUnsupportedOperationException; calling a second comparison on a closed filter throwsIllegalFilterStateException. The rule exists so a typo (where("x").eq(1).eq(2)) fails loudly rather than silently overwriting the first comparison.
Both artifacts are published under org.smallmind. Depend on one,
the other, or both.
<dependency>
<groupId>org.smallmind</groupId>
<artifactId>mongodb-utility</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.smallmind</groupId>
<artifactId>mongodb-throng</artifactId>
<version>${project.version}</version>
</dependency>Transitively each pulls in the driver artifacts
(bson, mongodb-driver-core, mongodb-driver-sync) at the versions
declared by the parent POM, plus smallmind-nutsnbolts for shared
utilities (pattern spread expansion, generic-type reflection, field
accessors, formatted exceptions).
Optional dependencies:
-
mongodb-utilitydeclaresspring-beansas optionalcompile. The SpringFactoryBeanclasses require it; programmatic use of the enums (MongoAcknowledgment) and plain value objects (MongoServer) does not. -
mongodb-throngdeclarestools.jackson.core:jackson-databindas optional.org.smallmind.mongodb.throng.json.JsonUtilityonly compiles when Jackson is on the classpath.
-
A MongoDB cluster reachable from the application. The
utilitymodule builds settings for plain TCP, SSL (with an optionalcertResource), and SCRAM-SHA-1 authentication. Other authentication mechanisms must be plugged into a caller-suppliedMongoCredential. -
Java reflection access to the
@Entity/@Embeddedclasses' private fields and no-arg constructors. Throng reads and writes fields throughFieldUtility.getFieldAccessors, with method handles created from its ownMethodHandles.Lookup; there is noUnsafeshortcut. -
Exactly one version of the MongoDB driver on the classpath. Mixing driver versions across modules is the common source of
NoSuchMethodErrorat client construction.
Both jars ship explicit module descriptors (org.smallmind.mongodb.utility and
org.smallmind.mongodb.throng, each exporting every package it contains). On the classpath
the descriptors are ignored. The repository-wide rules are in
Module Path And Classpath; this section lists what is specific
to these two modules.
Required modules. Both require the driver’s automatic modules org.mongodb.bson,
org.mongodb.driver.core, and org.mongodb.driver.sync.client, and re-export
org.smallmind.nutsnbolts (requires transitive). Driver types such as MongoClient,
Bson, and CodecRegistry appear in public signatures of both modules, but automatic
modules are never re-exported, so require the driver modules you use in your own
descriptor.
Optional modules. mongodb-utility declares requires static spring.beans for its
FactoryBean classes. mongodb-throng declares requires static tools.jackson.databind
for JsonUtility; Jackson is an explicit module, so if you use JsonUtility on a module
path, require tools.jackson.databind yourself or add it with --add-modules.
Packages these modules open. mongodb-utility opens
org.smallmind.mongodb.utility.spring to spring.core and spring.beans.
Packages you open. Throng constructs your @Entity and @Embedded classes and the
codecs named by @Codec, invokes their lifecycle callbacks, and reads and writes their fields,
all with its own access. Open each package holding mapped classes to
org.smallmind.mongodb.throng:
module com.example.app {
requires org.mongodb.bson;
requires org.mongodb.driver.core;
requires org.mongodb.driver.sync.client;
requires org.smallmind.mongodb.throng;
opens com.example.app.model to org.smallmind.mongodb.throng;
}Without it, building the class’s codec (in ThrongClient’s constructor) fails with
`IllegalAccessException: module com.example.app does not open com.example.app.model to module
org.smallmind.mongodb.throng. Throng does not need to read your module; the read edge is added
when the codec is built.
The fastest path is: wire a MongoClient through mongodb-utility,
instantiate a ThrongClient over it, and call typed CRUD.
<bean id="mongoServers"
class="org.smallmind.mongodb.utility.spring.MongoServerFactoryBean">
<property name="serverPattern" value="mongo#.internal:27017"/> (1)
<property name="serverSpread" value="1-3"/> (2)
</bean>
<bean id="mongoCredential"
class="org.smallmind.mongodb.utility.spring.MongoCredentialFactoryBean">
<property name="user" value="app-service"/>
<property name="password" value="${mongo.password}"/> (3)
<property name="source" value="admin"/> (4)
</bean>
<bean id="mongoWriteConcern"
class="org.smallmind.mongodb.utility.spring.MongoWriteConcern">
<property name="acknowledgment" value="MAJORITY"/> (5)
<property name="journaled" value="true"/>
</bean>
<bean id="mongoClientSettings"
class="org.smallmind.mongodb.utility.spring.MongoClientSettingsFactoryBean">
<property name="serverAddresses" ref="mongoServers"/>
<property name="mongoCredential" ref="mongoCredential"/>
<property name="writeConcern" ref="mongoWriteConcern"/>
<property name="sslEnabled" value="true"/>
<property name="connectionPoolMaxSize" value="50"/>
</bean>
<bean id="mongoClient"
class="org.smallmind.mongodb.utility.spring.MongoClientFactoryBean">
<property name="clientSettings" ref="mongoClientSettings"/> (6)
</bean>-
Template for the broker host names.
#marks the expansion point. -
The spread
1-3produces three addresses on port 27017. -
Plain string; the factory converts it to a
char[]when it constructs theMongoCredential. -
Authentication database. For SCRAM users defined in
admin, useadmin; for users defined in the application database, use the database name. -
An enum literal —
ZERO,ONE,TWO,THREE, orMAJORITY.withJournal(true)is applied only for journable levels (everything exceptZERO). -
MongoClientFactoryBeancallsMongoClients.create(settings)eagerly inafterPropertiesSetand callsclient.close()indestroy. The surrounding Spring context owns the lifecycle.
import org.bson.types.ObjectId;
import org.smallmind.mongodb.throng.mapping.annotation.Entity;
import org.smallmind.mongodb.throng.mapping.annotation.Id;
import org.smallmind.mongodb.throng.mapping.annotation.Property;
@Entity("orders") (1)
public class Order {
@Id (2)
private ObjectId id;
@Property("placed_at") (3)
private long placedAt;
@Property (4)
private String status;
public Order () {} (5)
public ObjectId getId () { return id; }
public void setId (ObjectId id) { this.id = id; }
public long getPlacedAt () { return placedAt; }
public void setPlacedAt (long placedAt) { this.placedAt = placedAt; }
public String getStatus () { return status; }
public void setStatus (String status) { this.status = status; }
}-
value()on@Entitynames the MongoDB collection. The annotation’spolymorphic()member is unused here and must stay at its default@Polymorphic()(empty). -
Exactly one
@Idfield is required. Its default storage name is_id; pass@Id("alternative_id")to override. -
A stored field whose BSON name differs from the Java field name.
-
No-arg
@Propertyuses the Java field name (status) as the BSON name. -
Throng constructs entities reflectively with a no-arg constructor. It is required on both
@Entityand@Embeddedclasses.
import org.smallmind.mongodb.throng.ThrongClient;
import org.smallmind.mongodb.throng.ThrongOptions;
ThrongClient throng = new ThrongClient(
mongoClient,
"orders-db",
new ThrongOptions(false, true, true), (1)
Order.class); (2)-
storeNulls=false,createIndexes=true,includeCollation=true. -
Entity and embedded classes are registered up front. Any class not listed here produces
ThrongRuntimeException("Unmapped entity type(…)")at the first CRUD call.
import org.smallmind.mongodb.throng.query.Filter;
import org.smallmind.mongodb.throng.query.Query;
import org.smallmind.mongodb.throng.query.Sort;
List<Order> open = throng.find(
Order.class,
Query.with()
.filter(Filter.where("status").eq("OPEN"))
.sort(Sort.on().desc("placed_at")) (1)
.limit(50))
.asList(); (2)-
Sort by the BSON field name, not the Java field name. Throng does not translate Java field references in the DSL.
-
ThrongIterable.asList()eagerly drains the cursor.
A plain value object holding a (host, port) pair, default port
27017. It has a no-arg constructor for bean wiring and a convenience
(String, int) constructor. It is not consumed by the
MongoServerFactoryBean — which uses pattern/spread expansion to
produce ServerAddress[] directly — but is useful in custom wiring
that needs to aggregate hosts from multiple sources.
| Constant | Driver WriteConcern |
Journable |
|---|---|---|
|
|
no |
|
|
yes |
|
|
yes |
|
|
yes |
|
|
yes |
The enum is the contract for MongoWriteConcern.setAcknowledgment.
journable is consulted by MongoWriteConcern before it decides
whether to apply withJournal(true).
Spring FactoryBean<ServerAddress[]>. Parses a serverPattern
(mongo#.internal:27017 or a plain localhost) and an optional
serverSpread (1-3, a-c, 1,2,5) and emits the corresponding
array during afterPropertiesSet.
Parsing rules (mirroring the Kafka module’s equivalent):
-
No
#, no:— single address, port defaults to27017. -
No
#, with:— single address, host is the prefix, port is the suffix parsed asint. -
With
#, no:— one address per spread value, port defaults to27017. -
With
#and:— one address per spread value; the literal port after:applies to every address.
An empty or null serverPattern leaves serverAddresses at null.
getObject() is then null — callers that require a non-null result
must set the pattern explicitly.
|
Note
|
A |
Spring FactoryBean<MongoCredential>. Produces a single
MongoCredential via
MongoCredential.createScramSha1Credential(user, source, password.toCharArray()).
Every property is required; there are no defaults.
For authentication mechanisms other than SCRAM-SHA-1 (SCRAM-SHA-256,
X.509, Kerberos, AWS IAM), construct the MongoCredential directly
and inject it into MongoClientSettingsFactoryBean.setMongoCredential.
Spring FactoryBean<WriteConcern> with isSingleton() = false. The
contract is:
-
setAcknowledgment(MongoAcknowledgment)selects the level; -
setJournaled(boolean)asks for journal acknowledgment, but has no effect unless the chosen level is journable.
A journable level plus journaled=true emits
acknowledgment.getWriteConcern().withJournal(true); any other
combination returns acknowledgment.getWriteConcern() unchanged.
Spring FactoryBean<MongoClientSettings> with 20+ nullable setters.
Each non-null property applies to the appropriate sub-builder; every
null property leaves the driver’s default in place.
Behavior worth knowing:
-
SSL context — if
certResourceis set, the factory loads a trust store viaorg.smallmind.nutsnbolts.security.TrustManagerUtility.load()and installs anSSLContextinitialized with that trust manager. IfcertResourceis null, the default JSSE trust store is used. -
SSL enabled — controlled independently by
sslEnabled. SSL is only applied when the flag istrue; the trust material is loaded whenevercertResourceis set, regardless of the flag. -
Write concern — applied only if
writeConcernis non-null andwriteConcernEnabledis not explicitlyfalse. This lets an operator disable write-concern overrides without removing the bean reference. -
UUID representation — hard-coded to
UuidRepresentation.STANDARD. There is no property to override it. -
Codec registry — if
codecRegistryis set, it is prepended to the driver defaults viaCodecRegistries.fromRegistries(custom, MongoClientSettings.getDefaultCodecRegistry()). The composite wins for types the custom registry covers and falls through for everything else.
The full setter list (all accept the standard boxed types, all apply their value only when non-null):
| Setter | Type | Applied to |
|---|---|---|
|
|
client-wide codec registry |
|
|
SSL trust store |
|
|
|
|
|
|
|
|
client-wide read preference |
|
|
client-wide read concern |
|
|
client-wide write concern |
|
|
gate for applying |
|
|
read retry |
|
|
write retry |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Spring FactoryBean<MongoClient> that also implements
InitializingBean and DisposableBean. On context startup it calls
MongoClients.create(clientSettings) and holds the resulting
MongoClient; on context shutdown it calls client.close().
There is no reconnection, refresh, or reload behavior. Replacing
credentials or server lists at runtime requires either refreshing the
Spring context that owns the bean or building a new MongoClient
outside of Spring.
A representative end-to-end configuration:
<bean id="mongoServers"
class="org.smallmind.mongodb.utility.spring.MongoServerFactoryBean">
<property name="serverPattern" value="mongo#.prod.internal:27017"/>
<property name="serverSpread" value="1-3"/>
</bean>
<bean id="mongoCredential"
class="org.smallmind.mongodb.utility.spring.MongoCredentialFactoryBean">
<property name="user" value="${mongo.user}"/>
<property name="password" value="${mongo.password}"/>
<property name="source" value="admin"/>
</bean>
<bean id="mongoWriteConcern"
class="org.smallmind.mongodb.utility.spring.MongoWriteConcern">
<property name="acknowledgment" value="MAJORITY"/>
<property name="journaled" value="true"/>
</bean>
<bean id="mongoClientSettings"
class="org.smallmind.mongodb.utility.spring.MongoClientSettingsFactoryBean">
<property name="serverAddresses" ref="mongoServers"/>
<property name="mongoCredential" ref="mongoCredential"/>
<property name="writeConcern" ref="mongoWriteConcern"/>
<property name="readPreference">
<util:constant static-field="com.mongodb.ReadPreference.SECONDARY_PREFERRED"/>
</property>
<property name="sslEnabled" value="true"/>
<property name="retryWrites" value="true"/>
<property name="retryReads" value="true"/>
<property name="socketConnectTimeoutMilliseconds" value="5000"/>
<property name="serverSelectionTimeoutMilliseconds" value="15000"/>
<property name="connectionPoolMinSize" value="5"/>
<property name="connectionPoolMaxSize" value="50"/>
<property name="connectionPoolMaxConnectionLifeTimeSeconds" value="600"/>
</bean>
<bean id="mongoClient"
class="org.smallmind.mongodb.utility.spring.MongoClientFactoryBean">
<property name="clientSettings" ref="mongoClientSettings"/>
</bean>ThrongClient is the entry point for every typed operation. It is
constructed once per database, holds no connection state beyond what
the underlying driver maintains, and is safe to share across threads.
public ThrongClient(MongoClient mongoClient,
String database,
ThrongOptions options,
Class<?>... entityClasses)
throws ThrongMappingException, NoSuchMethodException,
InstantiationException, IllegalAccessException,
InvocationTargetException;Construction:
-
Resolves the
MongoDatabasefrom theMongoClient. -
Composes an initial
CodecRegistrythat prepends anArrayCodecProvider(respectingoptions.isStoreNulls()) to the database registry. -
Scans
entityClassestwice:-
first pass registers codecs for
@Embeddedclasses (ThrongEmbeddedUtility.generateEmbeddedCodec), producing either a plainThrongEmbeddedCodecor aThrongPolymorphicEmbeddedCodecdepending on whether the class has@Polymorphic(value = {…}); -
second pass registers
ThrongEntityCodecinstances for@Entityclasses and, whenoptions.isCreateIndexes()is true, callsIndexUtility.createIndexon the collection with the entity’s compound and single-field indexes.
-
-
Builds the final
CodecRegistryused by every CRUD call:ThrongDocumentCodec+ embedded codecs + driver registry
ArrayCodecProvider.
CRUD surface:
| Method | Behavior |
|---|---|
|
Counts documents satisfying |
|
Applies the query (filter, sort, projection, skip, limit, batch
size) and returns a lazy iterable that decodes each
|
|
Convenience over |
|
Encodes the entity into a |
|
Calls |
|
Calls |
|
Runs the pipeline against the entity’s collection and decodes each output document back into the same entity type. Use when the pipeline preserves the source schema. |
|
Runs the pipeline against the source entity’s collection and decodes
each output document into a separately registered result entity type.
Use when the pipeline reshapes documents (for example |
|
Note
|
|
Three flags:
| Flag | Meaning |
|---|---|
|
When |
|
When |
|
When |
ThrongOptions has a (boolean, boolean, boolean) constructor and
fluent setters (setStoreNulls, setCreateIndexes,
setIncludeCollation) that return this. Its no-arg constructor is
private; use the three-argument form.
@Entity(value)-
Class-level. Marks a top-level document.
-
value()— the collection name (required). -
polymorphic()— must be left at the default@Polymorphic(). An entity with a non-empty@Polymorphicfails mapping (see Limitations).
-
@Embedded-
Class-level. Marks a non-collection document type.
-
polymorphic()— optional. A non-emptyvalue()list triggers polymorphic encode/decode throughThrongPolymorphicEmbeddedCodec.
-
@Id(value = "_id")-
Field-level. Identifies the primary key field.
-
value()— the BSON name. Default_id. Exactly one@Idfield per@Entity; missing or duplicate throwsThrongMappingException.
-
@Property(value = "")-
Field-level. Declares a stored field.
-
value()— the BSON name. Empty (the default) means "use the Java field name."
-
@Codec(value)-
Field-level. Binds a specific
org.bson.codecs.Codec<?>to the field, overriding the registry.-
value()— the codec class. The codec is instantiated reflectively viaCodecUtility; a type mismatch between the codec’s encoder class and the field type throwsThrongMappingExceptionat registration.
-
@Polymorphic(value = {}, key = "")-
Class-level. Declares a polymorphic hierarchy on an
@Embeddedclass.-
value()— the permissible concrete subtypes. Empty disables polymorphism. -
key()— the discriminator field name in BSON. Empty means "use `java/object`" (the legacy default).
-
All four lifecycle annotations are @Entity-only; declaring any of
them on an @Embedded class fails mapping with
ThrongLifecycleRejection.reject.
@PreLoad-
Must be
static. Takes a singleBsonDocumentparameter. Fires before the entity is decoded. Use it to inspect or transform the raw BSON. @PostLoad-
Instance method, no arguments. Fires after the entity has been decoded. Use it to compute derived state or validate the loaded object.
@PrePersist-
Instance method, no arguments. Fires before the entity is encoded. Use it to stamp
updatedAtfields or validate state pre-write. @PostPersist-
Instance method. Takes a single
BsonDocumentparameter. Fires after the encodedBsonDocumenthas been produced but before it is handed to the driver. Rarely needed; most projects use@PrePersist.
@Indexed(IndexType value = ASCENDING, IndexOptions options = …)-
Field-level. Declares a single-field index.
@Index(String value, IndexType type = ASCENDING)-
Component of a compound-index declaration. Not a standalone field annotation.
@Indexes(Index[] value, IndexOptions options = …)-
Class-level (repeatable via
@AllIndexes). Declares a compound index comprising the listed@Indexelements and shared options. @AllIndexes(Indexes[] value)-
Class-level. Container annotation aggregating multiple
@Indexes. Required because@Indexesis itself an array wrapper and not directly@Repeatable-compatible with Java’s annotation inheritance semantics. @IndexOptions-
Carries the MongoDB driver’s full
IndexOptionssurface:background,unique,name,sparse,expireAfterSeconds,version,weights,defaultLanguage,languageOverride,textVersion,sphereVersion,bits,min,max,storageEngine,partialFilterExpression,collation,wildcardProjection,hidden. Every member has a default; only override the ones that deviate from MongoDB’s standard behavior. @Collation-
Embedded inside
@IndexOptions.collation(). Carries the locale and strength settings that the driver’sCollation.builder()understands. IndexType-
Six-case enum:
ASCENDING,DESCENDING,HASHED,TEXT,GEO2D,GEO2DSPHERE. Each case knows how to produce aBsonindex spec by delegating tocom.mongodb.client.model.Indexes.
An entity with single-field indexes, a compound index, and a lifecycle callback:
import org.bson.BsonDocument;
import org.bson.types.ObjectId;
import org.smallmind.mongodb.throng.index.IndexType;
import org.smallmind.mongodb.throng.index.annotation.Index;
import org.smallmind.mongodb.throng.index.annotation.IndexOptions;
import org.smallmind.mongodb.throng.index.annotation.Indexed;
import org.smallmind.mongodb.throng.index.annotation.Indexes;
import org.smallmind.mongodb.throng.lifecycle.annotation.PrePersist;
import org.smallmind.mongodb.throng.mapping.annotation.Entity;
import org.smallmind.mongodb.throng.mapping.annotation.Id;
import org.smallmind.mongodb.throng.mapping.annotation.Property;
@Entity("orders")
@Indexes( (1)
value = {@Index(value = "status"),
@Index(value = "placed_at", type = IndexType.DESCENDING)},
options = @IndexOptions(name = "status_placedAt_idx"))
public class Order {
@Id
private ObjectId id;
@Indexed (2)
@Property("customer_id")
private String customerId;
@Indexed(value = IndexType.DESCENDING,
options = @IndexOptions(background = true)) (3)
@Property("placed_at")
private long placedAt;
@Property
private String status;
@Property
private long updatedAt;
@PrePersist
private void touch () {
updatedAt = System.currentTimeMillis(); (4)
}
}-
Compound index on
status(ascending) +placed_at(descending), with an explicit name so migrations can reference it. -
Single-field ascending index on
customer_idwith default options. -
Single-field descending index on
placed_atbuilt in the background so index creation does not block. -
Lifecycle callback. Throng fires this before encoding the document on every
insertand before everyupdatethat uses the encoded-entity path — the typedUpdatesDSL does not dispatch lifecycle callbacks.
A Filter is built in three steps: pick a field, apply a comparison,
and (optionally) negate.
Filter f = Filter.where("status").eq("OPEN"); (1)
Filter g = Filter.where("price").gte(100).not(); (2)
Filter h = Filter.where("tags").in("urgent", "expedited"); (3)
Filter i = Filter.and( (4)
Filter.where("status").eq("OPEN"),
Filter.where("placed_at").gt(since));
Filter j = Filter.empty(); (5)-
Single comparison.
-
not()negates the current filter; only legal after a comparison.not()on an uninitialized filter throwsIllegalFilterStateException. -
in(Object…)andin(Iterable<?>)both exist. The iterable form is preferred when the values come from a collection. -
andandoraccept varargs; passing zero filters returnsFilter.empty(). Passing a filter that has not had a comparison applied throwsIllegalFilterStateException. -
"Match everything." Used as a filter on
count,find,update, ordeletewhen the caller wants to operate on the whole collection.
Supported comparisons:
| Method | MongoDB operator |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
A Query composes a Filter with paging and cursor controls.
Query q = Query.with()
.filter(Filter.where("status").eq("OPEN"))
.sort(Sort.on().desc("placed_at").asc("customer_id"))
.projection(Projections.with()
.include("customer_id", "status", "placed_at")
.exclude("_id"))
.skip(100)
.limit(25)
.batchSize(50);Defaults: skip=0, limit=0 (no limit), batchSize=0 (driver
default, usually 101 for the first batch). skip accepts a long
but the driver only honors an int-sized value.
Sort s = Sort.on()
.desc("placed_at")
.asc("customer_id");Order of invocation is the order applied by the driver.
Projections p = Projections.with()
.include("customer_id", "status")
.exclude("_id");Include and exclude follow MongoDB’s rules: mixing them is legal only
when excluding _id.
Updates u = Updates.of()
.set("status", "FULFILLED")
.inc("version", 1)
.setOnInsert("createdAt", now)
.push("history", event);Supported operators: set, unset, setOnInsert, inc, mul,
max, min, push, addToSet, pull, popFirst, popLast,
rename. Each call appends to an ordered list; toBsonDocument
combines the list via
com.mongodb.client.model.Updates.combine(…).
A Pipeline is an ordered list of aggregation stages, built with the
same fluent style as Filter, Sort, Updates, and Projections.
Stage builders accept the existing DSL types directly so a pipeline
can reuse a filter or sort already prepared elsewhere.
Pipeline pipeline = Pipeline.begin()
.match(Filter.where("status").eq("OPEN")) (1)
.sort(Sort.on().desc("placedAt")) (2)
.project(Projections.with().include("customer_id", "status", "total")) (3)
.skip(20)
.limit(10);
List<Order> page = throng.aggregate(Order.class, pipeline).asList(); (4)-
$match— reuses the standardFilterDSL. -
$sort— reuses the standardSortDSL. -
$project— reuses the standardProjectionsDSL. -
The pipeline output preserves the
Ordershape, so the single-classaggregatedecodes each result back into anOrderinstance.
Supported stages:
| Method | MongoDB stage |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
escape hatch — appends the supplied stage document verbatim |
For pipelines that reshape documents (most commonly $group), pair
the source entity with a separate result entity whose mapping matches
the output:
@Entity("category_rollups")
public class CategoryRollup {
@Id private String id; // receives the group key
@Property private Integer total;
@Property private Integer count;
/* getters/setters/no-arg */
}
ThrongClient throng = new ThrongClient(
mongoClient, "orders-db",
new ThrongOptions(false, true, true),
Order.class, CategoryRollup.class); (1)
List<CategoryRollup> rollups = throng.aggregate(
Order.class, CategoryRollup.class, (2)
Pipeline.begin()
.group("$category",
Accumulators.sum("total", "$amount"),
Accumulators.sum("count", 1))
.sort(Sort.on().desc("total"))).asList();-
Both entity classes must be registered with the client up front so each has a codec.
-
The first class identifies the source collection; the second identifies the decode shape applied to each pipeline output document.
The result entity’s @Id field receives the value of _id from each
output document — including null when the pipeline uses group(null, …)
to roll up the entire collection into a single bucket.
ThrongIterable<T> exposes two ways to consume a result set:
// Eager
List<Order> open = throng.find(Order.class, q).asList();
// Lazy
try (var cursor = throng.find(Order.class, q).iterator()) { (1)
while (cursor.hasNext()) {
process(cursor.next());
}
}-
The underlying
MongoCursoris closeable; rely on try-with-resources or explicit close when draining a long cursor.
Each next() call performs exactly one decode and fires @PreLoad /
@PostLoad once. A query with 10,000 matches and
Iterator#hasNext/next iteration decodes 10,000 times; asList()
is equivalent but eager.
ThrongClient builds a stacked CodecRegistry exactly once during
construction:
-
Driver base + array support. The first layer merges the database’s own registry with an
ArrayCodecProviderthat wraps every Java array type seen during mapping. ThestoreNullssetting flows into the array codec so that null elements in a stored array follow the same encoding rule as null scalar properties. -
Embedded codecs. The second layer adds one
ThrongEmbeddedCodec(orThrongPolymorphicEmbeddedCodec) per registered@Embeddedclass. Polymorphic variants dispatch at encode time by inspecting the runtime class and at decode time by reading the discriminator field (defaultjava/object, or whatever@Polymorphic.key()is). -
Document pass-through. The outermost layer adds a
ThrongDocumentCodecso that aThrongDocumentround-trips without further rewriting.
All filters, updates, and values pass through the outermost registry.
That is how a Filter.where("placed_at").gt(Instant.now()) is
encoded using the same rules that would encode a stored property.
TranslationUtility.fromBson invokes callbacks in this order during
decode:
-
@PreLoadstatic method (if present), with the rawBsonDocument. -
The codec decodes the document into a new instance.
-
@PostLoadinstance method (if present).
TranslationUtility.toBson invokes callbacks during encode:
-
@PrePersistinstance method (if present). -
The codec encodes the instance into a
BsonDocument. -
@PostPersistinstance method (if present), with the encodedBsonDocument.
Callbacks that throw propagate through the triggering operation
unchanged; a throwing @PrePersist short-circuits the insert before
anything touches the driver.
With storeNulls=false (the typical setting):
-
null property values are omitted from the encoded document;
-
decoding tolerates either a missing field or a BSON null — in both cases the Java field is left at its default (
nullfor references,0for primitives); -
null elements inside a stored array are dropped on encode.
With storeNulls=true:
-
null property values become BSON null;
-
absent fields still decode to the Java default.
The flag affects encode only; decode is symmetrical.
IndexUtility.createIndex collects the entity’s compound indexes
(from @Indexes/@AllIndexes) and single-field indexes (from
@Indexed), resolves each IndexType into its driver
Indexes.ascending / descending / hashed / text / geo2d /
geo2dsphere factory call, applies each @IndexOptions to a driver
IndexOptions, and calls MongoCollection#createIndex per entry.
If options.isIncludeCollation() is false, the @Collation on
each @IndexOptions.collation() is ignored.
Index creation is not transactional and is not idempotent across
schema changes. Renaming a field without dropping the old index
leaves orphan indexes in place; removing an @Indexed annotation
does not drop the server-side index.
-
ThrongClientis safe to share across threads. Its internal state (database handle, codec registry, codec map) is set once during construction and only read thereafter. -
Filter,Query,Sort,Projections, andUpdatesare single-use builders; do not mutate one from multiple threads. Each CRUD call is idiomatic: build the query, pass it in, discard. -
ThrongIterableand itsThrongIteratorwrap the driver’s ownFindIterable/MongoCursor; the cursor is not thread-safe and must be iterated from one thread.
The exceptions callers will see fall into four groups.
- Mapping
-
ThrongMappingException(checked) is raised duringThrongClientconstruction when an annotation is wrong, a codec cannot be resolved, an embedded class declares a lifecycle callback, or an entity has zero or multiple@Idfields. It extendsorg.smallmind.nutsnbolts.lang.FormattedException, so callers declare or catch it. - Reflection
-
NoSuchMethodException,InstantiationException,IllegalAccessException, andInvocationTargetExceptionpropagate fromThrongClientconstruction when an@Entity,@Embedded, or@Codecclass lacks a no-arg constructor or access cannot be granted. - Runtime
-
ThrongRuntimeExceptionis raised for unmapped entity lookups (Unmapped entity type(…)), codec dispatch failures in polymorphic encode, and reflection errors inside lifecycle execution. Extendsorg.smallmind.nutsnbolts.lang.FormattedRuntimeException. - Filter
-
IllegalFilterStateException(runtime) is thrown when a comparison is applied to a closed filter or whennot()is applied to an uninitialized one.UnsupportedOperationExceptionis thrown byFilter.toBsonDocumentwhen the filter has never had a comparison applied — callers compose queries such that every leaf filter has exactly one comparison. - Driver
-
MongoExceptionand its subclasses pass through unchanged from the underlying driver.DuplicateKeyUtility.idDuplicateKeyExceptionis a small helper for detecting error code 11000 (E11000 duplicate key error) in aMongoWriteException.
ThrongMappingException: Missing id property-
The entity has no
@Idfield. Add one or, if the entity is intended to be embedded rather than top-level, change the annotation from@Entityto@Embedded. ThrongMappingException: More than one id property-
The entity has multiple
@Idfields. Keep exactly one. ThrongMappingException: Lifecycle methods are not supported on embedded types-
An
@Embeddedclass declares@PrePersist,@PostPersist,@PreLoad, or@PostLoad. Move the behavior to the parent@Entity— a callback on the parent sees the whole document, including the embedded subtree. ThrongMappingException: Polymorphism is not supported on entities-
An
@Entitydeclares@Polymorphic(value = {…}). Entities must not use@Polymorphic. If the hierarchy is a top-level collection, store the discriminator as an ordinary field and dispatch application-side; if the hierarchy is embedded, move it into an@Embeddedclass that can declare@Polymorphic. ThrongRuntimeException: Unmapped entity type(…)-
A CRUD call referenced a
Classthat was not passed in theentityClassesvararg to theThrongClientconstructor. Add it. IllegalAccessException: module … does not open … to module org.smallmind.mongodb.throng-
The application runs on a module path and has not opened the package holding its mapped classes. Open it to
org.smallmind.mongodb.throng; see Module Path. IllegalFilterStateException: The filter(…) is closed-
A second comparison was applied to a filter that already had one.
Filter.where("x").eq(1).eq(2)is not legal. Split into two filters and combine withFilter.and(…). IllegalFilterStateException: The filter(…) is incomplete-
A comparison-less filter was passed to
Filter.and,Filter.or, ornot(). Apply a comparison method before composing. UnsupportedOperationExceptionfromFilter.toBsonDocument-
Same root cause as the incomplete-filter case, surfaced when the filter is handed to
count/find/update/deletewithout a comparison. Add a comparison or useFilter.empty()to match all documents. ThrongRuntimeExceptionwrapping anExecutionExceptionduring decode-
A lifecycle method threw. The underlying exception is the
cause; fix the callback and retry. NumberFormatExceptionduring Spring context startup-
MongoServerFactoryBean’s pattern has a `placed after the:port separator. Move theleft of the:. ConfigException: No bootstrap hostsatMongoClientconstruction-
MongoClientSettingsFactoryBean.serverAddressesis null or empty. ConfirmMongoServerFactoryBean.serverPatternis set and the spread expression evaluates to at least one value. MongoWriteExceptionwith code11000-
Duplicate key — a unique index refused the write. Use
DuplicateKeyUtility.idDuplicateKeyException(mongoWriteException)to classify.
- No polymorphism for
@Entity -
@Polymorphicis an@Embedded-only feature. Top-level hierarchies must encode their discriminator as an ordinary property and dispatch application-side. - No lifecycle callbacks for
@Embedded -
Lifecycle behavior must live on the parent
@Entity. The rejection is enforced byThrongLifecycleRejection.rejectduring codec generation. - Partial support for generic containers
-
List,Map, and similar containers whose element type is@Embeddedcompile and run but do not participate in automated index processing — indexes declared on the embedded element type are not collected by the parent entity. Containers whose element type uses@Codecwill throw a type-mismatch exception at mapping time. The documented workaround is a typed subclass of the container with a parameterized codec, and — for@Embeddedelement types — to declare the required indexes on the parent entity using@Indexes/@AllIndexeswith dotted field paths. skipis effectivelyint-
Query.skipaccepts alongbut the underlying driver only honors anint. There is aTODOinQuery.javarecording the gap; do not pass values beyondInteger.MAX_VALUE. - No
aggregate/watchsurface -
Pipelines, change streams, and bulk writes are not exposed through
ThrongClient. Use the driver’sMongoClientdirectly for those operations. - SCRAM-SHA-1 only in the credential factory
-
MongoCredentialFactoryBeanhard-codes SCRAM-SHA-1. For SCRAM-SHA-256, X.509, Kerberos, AWS IAM, or OIDC, construct theMongoCredentialdirectly and inject it intoMongoClientSettingsFactoryBean. - UUID representation is pinned
-
MongoClientSettingsFactoryBeanhard-codesUuidRepresentation.STANDARD. There is no property to override it. Applications reading legacy data encoded with a different representation need to constructMongoClientSettingsdirectly. - No connection-string parser
-
The settings factory does not accept a
mongodb:///mongodb+srv://URI. Its inputs are typed components. - Compile-time dependency on Spring
-
mongodb-utility’s factory classes require `spring-beans. The dependency isoptionalin the POM, but the classes do not compile without it.
| Setting | Default | Where set |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Hard-coded. |
|
create in |
|
|
|
|
|
Java field name (empty triggers fallback) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Before shipping an integration:
-
Confirm the
MongoServerFactoryBeanproduces a non-emptyServerAddress[]— log the array at startup if needed. -
Pick a
MongoAcknowledgmentconsistent with the write durability your service requires, and setjournaledonly when the chosen level is journable. -
Pass every
@Entityand@Embeddedclass your service uses to theThrongClientconstructor — unregistered classes fail at first access. -
Set
createIndexes=truefor services that own the schema; set it tofalsefor readers that share a collection with an authoritative writer. -
For each
@Entity, confirm exactly one@Idand no@Polymorphic; for each@Embedded, confirm no lifecycle annotations. -
Verify the filter/update DSLs use BSON field names, not Java field names — Throng does not translate.
-
Close any
ThrongIteratoryou iterate manually;asList()closes internally. -
Close the surrounding Spring context on shutdown so the
MongoClientFactoryBean.destroyruns and drains the driver’s connection pool.
smallmind-mongodb turns the two rote jobs of using the MongoDB
Java driver — standing up a MongoClient and mapping Java classes
to documents — into two small, orthogonal modules. mongodb-utility
is a set of Spring FactoryBean implementations that produce
ServerAddress[], MongoCredential, WriteConcern,
MongoClientSettings, and a managed MongoClient. mongodb-throng
is an annotation-driven mapper whose ThrongClient vends typed
CRUD over @Entity classes, with fluent DSLs for filters, updates,
sorts, and projections, all composed over the driver’s own
CodecRegistry. Together they cover the path from XML configuration
to typed database access without the driver’s builder vocabulary
showing up in calling code.