Diffsert documentation
User guide
Diffsert writes MongoDB documents so that only real changes reach the oplog, change streams and Debezium. This guide explains how it decides what changed, every option, the Spring integration, and the pitfalls that make unchanged documents look changed.
Written for Diffsert 0.3.0. Features and behavior marked with a version, such as 0.3.0, are new or changed in that version.
What Diffsert is for
Many applications write the same documents again and again: a sync job copies another database into MongoDB
every hour, an import reloads a product catalog, a read model is rebuilt from its source. With save()
or replaceOne, every one of those writes replaces the whole document. MongoDB records the full
document in the oplog, and change streams and Debezium report a replace event, whether anything
changed or not.
Diffsert writes the same documents, but MongoDB records only what changed:
- An unchanged document causes no write and no event.
- A changed document produces an
updateevent that lists only the changed fields. - A new document produces an
insertevent, as before.
Use it when you write whole documents, mapped from DTOs, entities or another system, and
something downstream reacts to changes. You don't need it if you already send targeted updates
such as $set on single fields, or if documents are written once and never again.
Diffsert compares documents exactly, as BSON: field by field, including field order and value types. It doesn't know what your fields mean. Most surprises come from that, so What counts as a change is worth reading before you start.
How it works
Every write is an updateOne by _id with an aggregation pipeline, instead of a replacement:
db.customers.updateOne(
{ _id: "c1" },
[{ $replaceWith: { $literal: <new document> } }],
{ upsert: true })
The stored result is the same document a replace would produce. But for pipeline updates, MongoDB 5.0 and later
compare the result with the stored document and write only the difference to the oplog. Change streams turn
that difference into an update event. If the result is identical, the update is a no-op: the
document is matched but not modified, and no event is emitted.
$literal makes sure values are written as they are: a string such as "$5 off" is never
evaluated as an expression.
With ignored, preserved or version fields configured, the pipeline does more before anything is written:
- It copies the stored values of preserved fields into the new document.
- It compares the result with the stored document, leaving out the ignored fields, the version field and the preserved fields the stored document already has, whose values come from there anyway.
- If nothing else differs, it keeps the stored document as it is. That is a no-op, even though the ignored fields differ.
- Otherwise it writes the result, with the version field incremented if there is one.
- Find the stored document by
_id -
Stored document found?
noINSERTED · insert eventwith
update: NOT_FOUND, no event - yesCopy back the stored preserved fields
- Anything else differs?ignored, version and preserved fields left out noUNCHANGED · no eventthe stored document stays as it is
- yesWrite the result, version + 1
- MongoDB diffs it against the stored one deltaUPDATED · update eventwith only the changed fields
replace instead of an update.
DiffsertWriter.buildPipeline(document) returns the exact pipeline for a document; its Javadoc
explains each stage. What the server reports decides the outcome of a write:
| Server result | Outcome | Change event |
|---|---|---|
| Inserted by the upsert | INSERTED | insert |
| Matched and modified | UPDATED | update, sometimes replace (see Change streams) |
| Matched, not modified | UNCHANGED | none |
| Not matched, no upsert | NOT_FOUND | none |
Installation
Diffsert has three modules on Maven Central, under the group id dev.jbaby. Pick one:
| Artifact | Use it for | Brings in |
|---|---|---|
diffsert-spring-boot-starter | A Spring Boot 4 application | diffsert-spring-data, Boot's MongoDB starter |
diffsert-spring-data | Spring Data MongoDB without Boot's auto-configuration | diffsert-core, Spring Data MongoDB |
diffsert-core | The plain MongoDB Java driver, no Spring | mongodb-driver-sync |
<dependency>
<groupId>dev.jbaby</groupId>
<artifactId>diffsert-spring-boot-starter</artifactId>
<version>0.3.0</version>
</dependency>
implementation("dev.jbaby:diffsert-spring-boot-starter:0.3.0")
Requirements:
- Java 21 or later.
- MongoDB 5.0 or later. Change streams, and therefore Debezium, need a replica set; a single-node replica set is enough for development. The writes themselves also work on a standalone server.
- Spring Boot 4.0 and Spring Data MongoDB 2025.1 for the Spring modules. Earlier Spring versions are not supported.
The behavior Diffsert relies on, MongoDB writing only the difference to the oplog, is a server implementation detail, not a documented guarantee. That's why every supported server line is tested: CI runs all tests against MongoDB 5.0, 6.0, 7.0, 8.0, 8.2, 8.3 and 9.0, on every change and weekly.
Getting started
The examples write customers from a sync job. Each run has a jobRunId and stamps every document with
_createdAt and _updatedAt. These fields differ on every run, so they are configured not
to count as a change on their own.
With Spring Boot
Add diffsert-spring-boot-starter. It creates a Diffsert bean from your application's MongoTemplate.
diffsert:
ignore-fields: jobRunId, _updatedAt # alone, these are not a change
preserve-fields: _createdAt # the stored value wins once set
@Document("customers")
public record CustomerDto(
@Id String id,
String name,
String city,
String jobRunId,
@Field("_createdAt") Instant createdAt,
@Field("_updatedAt") Instant updatedAt) {
}
@Component
class CustomerSync {
private final Diffsert diffsert;
CustomerSync(Diffsert diffsert) {
this.diffsert = diffsert;
}
void write(List<CustomerDto> batch) {
BatchWriteResult result = diffsert.upsertAll(batch, CustomerDto.class);
// requested=1000, inserted=3, updated=12, unchanged=985, notFound=0
}
}
The Spring Boot starter section lists everything else the starter configures.
With Spring Data, without Boot
Add diffsert-spring-data and create the Diffsert yourself:
@Bean
Diffsert diffsert(MongoTemplate mongoTemplate) {
return new Diffsert(mongoTemplate, DiffsertOptions.builder()
.ignoreForChangeDetection("jobRunId", "_updatedAt")
.preserveExistingValue("_createdAt")
.build());
}
With the plain driver
Add diffsert-core. DiffsertWriter takes Documents and the collection to write to:
DiffsertWriter writer = new DiffsertWriter(DiffsertOptions.builder()
.ignoreForChangeDetection("jobRunId", "_updatedAt")
.preserveExistingValue("_createdAt")
.build());
MongoCollection<Document> customers = client.getDatabase("app")
.getCollection("customers");
BatchWriteResult result = writer.upsertAll(customers, documents);
The collection is passed with every call, so its codecs and write concern apply as you configured them. The
write concern must be acknowledged: with w: 0, a write doesn't tell what it did, so Diffsert rejects
it before writing. If you build the documents yourself, read Write Documents built with Jackson.
Writing documents
Diffsert method | What it does |
|---|---|
upsert(entity) | Inserts or updates one entity in the collection of its class. |
upsert(entity, "customers") | The same, with an explicit collection. |
update(entity) | Updates the document if it exists; never inserts. |
upsertAll(entities, CustomerDto.class) | Inserts or updates all entities with one bulk write, in the collection of the class. |
upsertAll(entities, "customers") | The same, with an explicit collection. |
updateAll(...) | Updates all that exist with one bulk write; never inserts. |
toWriteModels(entities, upsert) | Builds the write models without executing them, see Transactions and bulk writes. |
toDocument(entity) | The document that would be written. |
DiffsertWriter has the same methods for Documents, with the collection as the first
argument, such as upsertAll(collection, documents), plus buildPipeline(document).
diffsert.writer() returns the writer a Diffsert uses.
Collections. With a class, the collection is the one Spring Data maps the class to:
@Document("customers"), or the name derived from the class.
Ids. Every document needs an _id, and every entity an id value. Documents are
matched by _id only. Diffsert doesn't generate ids: a document or entity without one is rejected.
Upsert or update. upsert inserts documents that don't exist yet.
update skips them and reports them as NOT_FOUND, for jobs that only enrich documents
another process creates.
Results. Single writes return a WriteOutcome. Batch writes return a BatchWriteResult:
| Field | Meaning |
|---|---|
requested() | Documents passed in. |
inserted() | New documents inserted by the upsert; insertedIds() has their ids. One insert event each. |
modified() | Existing documents that really changed. One change event each. |
unchanged() | Existing documents left as they were. No events. |
notFound() | Documents that didn't exist and weren't inserted, with updateAll. |
matched() | Documents that already existed: modified() + unchanged(). |
toString() prints requested=1000, inserted=3, updated=12, unchanged=985, notFound=0,
and plus(other) adds up the results of several batches.
Batches. Each upsertAll or updateAll call is one bulk write.
Bulk writes are unordered by default: MongoDB may apply them in any order and continues after a failed
document. With ordered(true) (property diffsert.ordered), it stops at the first error.
The driver splits very large bulk writes into several commands on its own; the sync job Diffsert was extracted
from writes 1,000 documents per call.
Threads. Diffsert and DiffsertWriter are immutable and thread-safe.
Methods such as withOptions(...) and withListener(...) return a new instance.
What counts as a change
MongoDB compares the document Diffsert would write with the stored one. Every difference counts, except in ignored fields, the version field and preserved fields the stored document already has. Field by field, for one customer document:
More cases, in replace mode, the default:
| Stored | New | Result |
|---|---|---|
{ city: "Berlin" } | { city: "Berlin" } | Unchanged |
{ city: "Berlin" } | { city: "Hamburg" } | Changed: city |
{ a: 1, b: 2 } | { b: 2, a: 1 } | Changed: the field order differs |
{ tags: ["a", "b"] } | { tags: ["b", "a"] } | Changed: array order matters |
{ phone: null } | { } | Changed: phone is removed. null is a value, not a missing field |
{ day: ISODate(…) } | { day: "2026-10-01" } | Changed: a date is not a string |
{ count: 1 } (int) | { count: 1 } (long) | Changed, unless ignored, preserved or version fields are configured: then equal numbers count as unchanged, and the stored type stays |
{ jobRunId: "run-1" } | { jobRunId: "run-2" } | Unchanged if jobRunId is ignored |
Nested documents and arrays are compared the same way, all the way down. The change event reports them by path,
such as address.street or tags.2.
So keep what you write stable: the same field order, the same types, and null handled the same way
on every run. Troubleshooting lists the usual causes when every document is
reported as changed.
_id comes first. MongoDB always stores _id as the first field, so
Diffsert writes it first, wherever your document has it 0.2.0.
With 0.1.x, put it first yourself: anywhere else, the field order differs on every write, every write counts
as a change, and the event lists _id as updated.
Replace and merge mode
The mode decides what happens to fields that the stored document has but the new one doesn't.
- Replace (default): the new document is the full new state. Fields missing from it are removed, and the event lists them in
removedFields. - Merge (
merge(), propertydiffsert.mode: merge): the new document's fields are set on top of the stored document. Fields only the stored document has are kept.
// stored, creditLimit is written by the billing service
{ _id: "c1", name: "Acme", city: "Berlin", creditLimit: 5000 }
// new
{ _id: "c1", name: "Acme", city: "Hamburg" }
// replace: updatedFields { city }, removedFields [creditLimit]
{ _id: "c1", name: "Acme", city: "Hamburg" }
// merge: updatedFields { city }
{ _id: "c1", name: "Acme", city: "Hamburg", creditLimit: 5000 }
Merge mode works on top-level fields: a nested document in the new document replaces the stored one as a whole. Existing fields keep their stored position, so a different field order alone is no change. And merge mode can't remove a field, because leaving a field out keeps the stored value. Use it when other processes write their own top-level fields into the same documents.
Ignored fields
Some fields change on every run without meaning anything, such as a run id or a "synced at" time.
ignoreForChangeDetection(...) (property diffsert.ignore-fields) leaves them out of the
comparison:
- If only ignored fields differ, nothing is written and no event is emitted. The stored document keeps its old values.
- If anything else differs, the ignored fields are written along with the real changes, and appear in the event's
updatedFieldsif their value changed.
So after a run, _updatedAt tells you when the document last really changed, and jobRunId
which run made that change. Neither tells you which run last saw the document. To find documents the source no
longer has, see Detect records deleted at the source.
Ignored fields must be top-level field names: not _id, without dots, not starting with $.
Updating a field on every write
If a field should move on every write, don't ignore it. It then counts as a change whenever its value differs,
and since a timestamp differs on every run, every document is written every time. Each write produces an
update event with that field, plus any real changes. You keep small update events, but lose "no
write, no event": consumers and the oplog see every document again.
With auditing, @LastModifiedDate fields are always ignored. To move such a
field on every write, drop the annotation and set the value yourself.
Preserved fields
preserveExistingValue(...) (property diffsert.preserve-fields) keeps the stored value
of a field once it has one. That's what _createdAt needs:
- On insert, the new document's value is written.
- After that, the stored value is kept, whatever the new document contains. A different value doesn't count as a change, so a preserved field doesn't need to be ignored as well.
- If the stored document doesn't have the field yet, for example because it was written before the field existed, the new value is written. That counts as a change, so it happens once, with the next write.
- Leaving the field out of the new document doesn't remove it, not even in replace mode, and alone it's no change 0.3.0. With a real change in replace mode, the field is then written as the last field.
The last point also protects fields that another process writes: in replace mode, a preserved field is never removed, although your documents don't have it.
Version field 0.2.0
A version field counts the real changes of a document. Configure it with versionField("version")
(property diffsert.version-field); entities use their @Version property
automatically.
- It doesn't count as a change, and the value in the new document is ignored.
- A real change sets it to the stored value + 1. The stored type is kept: an int stays an int, a long a long.
- An insert, or a stored document without a version, gets the initial value: 0, as a long.
versionField("version", 1L)starts at 1; anIntegerinitial value, such asversionField("version", 0), writes ints. - A no-op leaves it as it is, including a write where only ignored fields differ.
- If the stored value isn't a number (a date isn't either 0.3.0), a write with a real change fails.
| Write | Stored version | Event |
|---|---|---|
| First write | 0 | insert |
| Same data, next run | 0 | none |
city changed | 1 | update: city, jobRunId, _updatedAt, version |
With @Version entities
For an entity with a @Version property, Diffsert uses that property's field as the version field and
starts where save() starts: at 0 for Long and Integer, at 1 for primitive
long and int. Applications that write the same documents with save() keep
working:
- A document inserted by Diffsert isn't new for
save(), sosave()updates it instead of failing with a duplicate key. - Every real change by Diffsert moves the version. An application holding an older version gets an
OptimisticLockingFailureExceptionfromsave()instead of overwriting the change.
Diffsert itself doesn't check the version, like MongoTemplate.updateFirst: its writes always win.
The version of the entity you pass in is ignored, and it isn't updated after the write. A configured version
field that differs from the entity's @Version field is rejected. If the application also writes
with save(), keep the type key, see Spring Data entities.
Spring Data entities
Diffsert converts entities with Spring Data's MongoConverter, like save():
@Id, @Field, custom converters and your mapping configuration apply.
toDocument(entity) shows the document that would be written.
- Only the conversion is like
save(). Entity callbacks (BeforeConvertCallback,BeforeSaveCallback,AfterSaveCallback), validation and mapping events (BeforeSaveEvent,AfterSaveEventand the others) don't run. Set values that a callback would set, such as a tenant field, before writing, and validate entities yourself. Auditing is handled separately, see Auditing. - Null properties are left out, as with
save(). In replace mode, a property that becomesnulltherefore removes the stored field, which appears inremovedFields.@Field(write = Field.Write.ALWAYS)writesnullinstead. - The type key
_classis removed by default, so documents don't change when you rename or move a class. Keep it withwithTypeKeyRemoved(false)(propertydiffsert.remove-type-key: false) if you read the documents polymorphically, or if your application also writes them withsave(). Otherwise_classcounts as a change whenever the other side wrote last. Documents are written as they are, without conversion. The configured options apply, but nothing is derived from annotations.- One batch can mix entity types as long as they derive the same options, that is the same auditing fields and version field. Otherwise write them in separate batches.
- Write concern: writes use the write concern of the client or database, for example
?w=majorityin the connection string. One set on the template withsetWriteConcernor aWriteConcernResolverdoesn't apply; usewithWriteConcern(WriteConcern.MAJORITY)0.3.0. With the starter, call it where you inject the bean, so listeners and metrics stay attached:this.diffsert = diffsert.withWriteConcern(...).
optionsFor(CustomerDto.class) 0.2.0 returns the
options Diffsert uses for a type: the configured ones, plus the fields derived from auditing annotations and
@Version.
Auditing 0.2.0
Spring Data's auditing annotations record who created or changed a document, and when. With Diffsert,
@LastModifiedDate moves only when something really changed:
| Annotation | Handled as | Effect |
|---|---|---|
@CreatedDate, @CreatedBy | Preserved field | Set when the document is inserted, then kept |
@LastModifiedDate, @LastModifiedBy | Ignored field | Written only together with a real change |
With the Spring Boot starter, @EnableMongoAuditing is all it takes:
@Configuration
@EnableMongoAuditing
class AuditingConfig {
}
@Document("orders")
public record Order(
@Id String id,
String status,
@CreatedDate Instant createdAt,
@LastModifiedDate Instant updatedAt) {
static Order of(String id, String status) {
return new Order(id, status, null, null);
}
}
diffsert.upsertAll(orders, Order.class); // leave the audit fields null
The starter uses the bean mongoAuditingHandler that @EnableMongoAuditing registers;
a JPA auditing handler in the same application is left alone. Without Boot, pass that handler yourself:
@Bean
Diffsert diffsert(MongoTemplate mongoTemplate,
@Qualifier("mongoAuditingHandler") AuditingHandler auditingHandler) {
return new Diffsert(mongoTemplate).withAuditing(auditingHandler);
}
What happens on a write:
- Diffsert can't know whether a document exists before it writes, so it marks every entity like
save()marks a new one: created and modified fields get the current time from yourDateTimeProviderand the user from yourAuditorAware. Preserving and ignoring then keep the right values on the server. - Mutable entities get the values set in place. Records and other immutable classes need a wither or a single constructor, as with
save(). A second, shorter constructor makes Spring fail with "no setter, wither or copy constructor"; use a static factory such asOrder.of(...)instead. - With
setModifyOnCreation(false)on the handler, Diffsert still sets the modified fields to the current time, also when the entity already has values in them (for example after loading it) 0.3.0, because it can't tell an insert from an update. - A stored document without a created date, for example from before auditing was enabled, gets the current time with its next write. That write counts as a change once.
- Only top-level properties are supported: an entity with auditing annotations inside an embedded object is rejected.
Auditing doesn't apply to Documents. To get the same behavior, set the fields yourself and configure
_updatedAt as ignored and _createdAt as preserved, as in
Getting started. For a @LastModifiedDate that should move on every write, see
Updating a field on every write.
Spring Boot starter
The starter auto-configures a Diffsert bean when the application has a single MongoOperations bean, such as Boot's MongoTemplate, or one marked @Primary. With several and none of them primary, for example one template per database, it backs off 0.3.0: define a Diffsert bean per template yourself. Properties:
| Property | Default | Meaning |
|---|---|---|
diffsert.mode | replace | replace or merge, see Replace and merge mode |
diffsert.ignore-fields | none | Fields that alone don't count as a change, see Ignored fields |
diffsert.preserve-fields | none | Fields whose stored value is kept, see Preserved fields |
diffsert.version-field 0.2.0 | none | A field that counts real changes, see Version field |
diffsert.ordered | false | Ordered bulk writes stop at the first error |
diffsert.remove-type-key | true | Remove _class from converted entities |
- Options in code: define a
DiffsertOptionsbean. It replaces all option properties above; onlyremove-type-keystill applies. With severalDiffsertOptionsbeans, for example for writers of your own, the one marked@Primaryis used, and without one the properties 0.3.0. - Listeners: every
DiffsertListenerbean is called after each write, in@Order. A failing listener is logged as a warning and affects neither the write, the caller nor the other listeners. - Metrics: with Micrometer and a
MeterRegistry, the counterdiffsert.documentscounts written documents, tagged withcollectionandoutcome(inserted,updated,unchanged,not_found). - Auditing 0.2.0: with
@EnableMongoAuditing, auditing is handled automatically. - Your own bean: a
Diffsertbean of your own replaces the auto-configured one, including listeners and metrics. Attach them withwithListener(...), or define aDiffsertOptionsbean instead.
@Bean
DiffsertOptions diffsertOptions() {
return DiffsertOptions.builder()
.ignoreForChangeDetection("jobRunId", "_updatedAt")
.preserveExistingValue("_createdAt")
.build();
}
@Bean
DiffsertListener logWrites() {
return (collection, result) -> log.info("{}: {}", collection, result);
}
Listeners and metrics
A DiffsertListener is called after every write, with the collection name and a
BatchWriteResult. A single write is reported as a result with requested = 1.
Diffsert logging = diffsert.withListener((collection, result) ->
log.info("{}: {}", collection, result));
// customers: requested=1000, inserted=3, updated=12, unchanged=985, notFound=0
- It runs on the writing thread, after the write.
- If a bulk write fails, the listener first receives the result of the documents that were written, then the exception is thrown. A single write that fails isn't reported, not even after a write concern error, see Failed writes.
withListener(...)replaces the current listener. To notify several, call them from one listener; the starter does that for listener beans.- Outside the starter, an exception thrown by a listener reaches the caller, although the write has already happened.
- Write models from
toWriteModels(...)aren't reported, because you execute them. - In a transaction, listeners are called when the write runs, so they also count writes that are rolled back later.
With the starter and Micrometer, DiffsertMetrics is such a listener; you can also attach it yourself
with withListener(new DiffsertMetrics(meterRegistry)).
Transactions and bulk writes
Diffsert writes go through MongoOperations, so they join a Spring-managed transaction like any template operation:
@Transactional
void importOrders(List<Order> orders, List<OrderLine> lines) {
diffsert.upsertAll(orders, Order.class);
diffsert.upsertAll(lines, OrderLine.class);
}
- This needs a
MongoTransactionManagerthat uses the sameMongoDatabaseFactoryas the template. - Change events appear when the transaction commits, still as deltas. A rollback produces none.
- Listeners and metrics count the writes when they run, including writes that are rolled back.
Without Spring, or to combine Diffsert's writes with other operations in one bulk write, build the write models and execute them yourself:
List<WriteModel<Document>> models = new ArrayList<>();
models.addAll(writer.toWriteModels(documents, true));
models.add(new DeleteManyModel<>(Filters.eq("status", "obsolete")));
try (ClientSession session = client.startSession()) {
session.withTransaction(() -> customers.bulkWrite(session, models));
}
buildPipeline(document) returns the update pipeline for one document, for an
updateOne of your own with the filter { _id: <the document's _id> }.
Change streams and Debezium
| Outcome | Change event |
|---|---|
INSERTED | insert, with the full document |
UPDATED | update with updatedFields, removedFields and truncatedArrays; for small documents sometimes replace |
UNCHANGED | none |
NOT_FOUND | none |
{ operationType: "update",
documentKey: { _id: "c1" },
updateDescription: {
updatedFields: { city: "Hamburg", jobRunId: "run-2",
_updatedAt: ISODate("2026-10-08T12:00Z") },
removedFields: [],
truncatedArrays: [] } }
- Paths: nested fields and array elements are reported by path, such as
address.streetortags.2. A shortened array appears intruncatedArrays. - Replace events still happen. MongoDB logs a delta only when it is smaller than the new document. For very small documents, or when almost every field changes, the event is a
replace. In a test with ten short fields, changing nine still gave anupdate. Treat areplaceas "anything may have changed". - Full documents are read later. With
fullDocument: "updateLookup", the full document in an update event is read when the event is read, not when the write happened, so it can already contain later changes.
Reacting to specific fields
A consumer that cares about certain fields checks the event's paths, and treats inserts and replaces as changes to everything:
switch (event.getOperationType()) {
case UPDATE -> {
UpdateDescription update = event.getUpdateDescription();
Set<String> paths = new HashSet<>(update.getUpdatedFields().keySet());
paths.addAll(update.getRemovedFields());
if (paths.stream().anyMatch(p -> p.equals("address")
|| p.startsWith("address."))) {
onAddressChanged(event.getDocumentKey());
}
}
case INSERT, REPLACE -> onAddressChanged(event.getDocumentKey());
default -> { }
}
With Debezium
Debezium's MongoDB connector reports both update and replace events as op: "u". What else an event carries depends on its capture.mode:
| Capture mode | Update event (Diffsert) | Replace event |
|---|---|---|
change_streams_update_full (default) | updateDescription, plus the full document in after | Full document in after, no updateDescription |
change_streams | updateDescription only, no after | Full document in after, no updateDescription |
*_with_pre_image (MongoDB 6.0+) | Additionally the old document in before | Additionally before |
- Unchanged documents produce no event in any mode, because nothing is written.
- Read changes from
updateDescription, not fromafter. In the default mode,afteris the whole document, so it doesn't show what changed. Debezium reads it from the collection when it processes the event, so it can already contain later changes, or benullif the document was deleted in the meantime, unless you setcapture.mode.full.update.type=post_image(MongoDB 6.0+). - No
updateDescriptionmeans a replace: treat every field as possibly changed, or comparebeforeandafterin a pre-image mode. - Check
change_streamspipelines before switching to Diffsert. Withsave(), every event carried the full document, even in this mode. With Diffsert, update events have noafter, andExtractNewDocumentStateemits only_idand the changed fields, nested ones as dotted keys. A sink that expects whole documents would write partial ones. ExtractNewDocumentStatekeeps onlyafterin the default mode. If consumers need the changed fields, copy them into the flattened record with the transform'sadd.fieldsoption.
Errors and retries
Rejected before writing
These problems are found before anything is written, and throw an IllegalArgumentException:
| Message starts with | Cause |
|---|---|
entity has no id, document has no _id | The id is missing or null. |
collection … has an unacknowledged write concern | The collection uses w: 0, which doesn't tell what a write did. 0.3.0 |
ignoredFields: only top-level field names other than _id are supported | The same for preservedFields and versionField: a dotted name, _id, a name starting with $, or a blank one. |
versionField '…' must not be an ignored or preserved field as well | One field configured twice. |
auditing field '…' of … is nested | An auditing annotation inside an embedded object. 0.2.0 |
entities in one batch must have the same auditing and version fields | Entity types with different derived options in one batch. 0.2.0 |
version field '…' is configured, but … | The configured version field differs from the entity's @Version field. 0.2.0 |
Failed writes
Driver exceptions are thrown as they are, not translated into Spring's DataAccessException:
- A single write throws a
MongoWriteException, for example for a duplicate key in a unique index. - A batch throws a
MongoBulkWriteException.getWriteErrors()lists each failed document with its index in the batch. Unordered batches, the default, still write all other documents; ordered ones stop at the first error. - Documents written before or besides the failed ones are reported to listeners and metrics before the exception is thrown.
- A write concern error, for example a
w: majoritytimeout, means the write was applied on the primary but not confirmed as required. In a batch, these writes are reported. A single write throws aMongoWriteConcernExceptionwithout reporting it: the driver doesn't say whether the document was changed.
Retries are safe
Writing the same document again changes nothing: the second write is a no-op, with no event and no new version. After a failure, you can write the whole batch again; only what is still missing or different is written.
Recipes
Write Documents built with Jackson
If you map DTOs to Documents yourself instead of using Spring Data's mapping, write them with
DiffsertWriter, or with Diffsert, which passes Documents through. For a
plain DTO such as record CustomerDto(String id, String name, String city):
private final ObjectMapper mapper = new ObjectMapper();
Document toDocument(CustomerDto dto, String jobRunId, Date now) {
Document doc = new Document("_id", dto.id()); // _id first, needed with 0.1.x
doc.putAll(mapper.convertValue(dto, new TypeReference<Map<String, Object>>() {}));
doc.remove("id");
return doc.append("jobRunId", jobRunId)
.append("_createdAt", now)
.append("_updatedAt", now);
}
_idfirst with 0.1.x: MongoDB stores_idas the first field, and anywhere else every write counts as a change. Diffsert 0.2.0 moves it to the front for you.- Stable field order. Jackson writes the properties of a class in the same order every time;
@JsonPropertyOrdermakes the order explicit. Don't build documents from aHashMapor aHashSet: their order can differ between runs. - Dates.
convertValueturnsjava.timevalues into numbers or strings, depending on theObjectMapper's configuration, not into BSON dates. Set date fields yourself, asDateorInstant. - Nulls. Decide whether null properties are written as
nullor left out (@JsonInclude(NON_NULL)), and keep it that way: switching changes every document that has such a field. - Numbers. Keep numeric types stable.
Document.parse(json), for example, picks int, long or double by value, so a number that grows past the int range changes its type.
Detect records deleted at the source
Unchanged documents aren't written, so "not written in this run" doesn't mean "gone at the source". Collect the ids you write, and delete the rest after the run:
Set<String> seen = new HashSet<>();
for (List<CustomerDto> batch : batches) {
diffsert.upsertAll(batch, CustomerDto.class);
batch.forEach(customer -> seen.add(customer.id()));
}
// only after the whole run succeeded
mongoTemplate.remove(Query.query(Criteria.where("_id").nin(seen)), CustomerDto.class);
Delete only after a complete, successful run: after a failed one, the set is incomplete. For large collections,
store the ids in a separate collection instead of one big $nin query.
Switch from save()
- Expect one round of updates. The first run updates every document whose stored form differs from what Diffsert writes, typically because
_classis removed, and emits one event for each. After that, only real changes produce events. Run it once before consumers rely on the new behavior, or keep the type key. - Update consumers. Events change from
replacewith the full document toupdatewithupdateDescription. Check consumers that read the full document, and Debezium setups, see With Debezium. - Ids:
save()generates missing ids, Diffsert requires them. - Callbacks and events: entity callbacks, validation and save events don't run, see Spring Data entities.
- Versioned entities: see With
@Versionentities.
Let two jobs write the same documents
When two jobs fill different top-level fields of the same documents, use merge mode for both, so that neither removes the other's fields:
// the CRM job writes name and city, the billing job creditLimit
Diffsert merging = diffsert.withOptions(
diffsert.options().toBuilder().merge().build());
merging.upsertAll(crmCustomers, "customers");
A field that both jobs write with different values changes back and forth, and produces an event every time.
Check which events your writes produce
To see what a write emits, for example in an integration test, open a change stream before writing and insert a marker document afterwards. Every event before the marker's belongs to your write:
BsonString marker = new BsonString("marker-" + UUID.randomUUID());
List<ChangeStreamDocument<Document>> events = new ArrayList<>();
try (var cursor = collection.watch().cursor()) {
diffsert.upsertAll(customers, CustomerDto.class);
collection.insertOne(new Document("_id", marker));
ChangeStreamDocument<Document> event;
while (!marker.equals((event = cursor.next()).getDocumentKey().get("_id"))) {
events.add(event);
}
}
collection.deleteOne(new Document("_id", marker));
This needs a replica set; with Testcontainers, start MongoDBContainer with withReplicaSet().
Troubleshooting
Every document is reported as UPDATED
Look at the events first: updatedFields and removedFields name exactly the fields that
differed. Or compare diffsert.toDocument(entity).toJson() with the stored document. Common causes:
- A field that changes on every run isn't ignored: a timestamp, a run id, a generated value.
- With 0.1.x:
_idisn't the first field of the document; the event then lists_id. _class: the application writes it withsave(), and Diffsert removes it, or the other way round.- The field order changed: a reordered DTO, a different mapping, a
HashMap. - The array order changes: lists built from a
HashSet, or source data without a fixed sort order. - The types differ from what's stored: int and long, double and decimal, string and date. Without ignored, preserved or version fields, a numeric type alone counts too.
nulland missing: the stored document has the field asnulland the new one leaves it out, or the other way round.
After you change the mapping, the first run updates every affected document once; that's expected. If the same documents are updated on every run, one of the causes above is at work.
A change wasn't written
- Only ignored fields differed, which is the point of ignoring them.
- The field is preserved: the stored value wins.
- Merge mode: fields left out of the new document are kept.
- Only a numeric type changed, such as
1to1L, while ignored, preserved or version fields are configured. Equal numbers then count as unchanged. - The collection has a case- or accent-insensitive default collation, and only the case or accents changed, such as
AcmetoACME, while ignored, preserved or version fields are configured. The comparison uses the collation, see Limitations. updateandupdateAlldon't insert; look forNOT_FOUND.
Replace events still appear
For small documents, or when almost every field changes, MongoDB logs a full replacement. That's expected; consumers should handle replace events.
No change events at all
- Change streams need a replica set; a standalone server has none.
UNCHANGEDwrites emit nothing, by design.- In a transaction, events appear only after the commit.
Limitations
- Ignored, preserved and version fields are top-level fields; nested ones such as
meta.updatedAtaren't supported. - Documents are matched by
_idonly. - Collections with a non-simple default collation: with ignored, preserved or version fields, the comparison uses the collation, so a change that it treats as equal, such as
AcmetoACMEwith a case-insensitive one, isn't written. Without these options, it is. String ids that differ only in case match the same document, as with any query, and the write fails because_idcan't change. - Sharded collections aren't tested. MongoDB requires the full shard key in the filter of an upsert, so upserts by
_idwork only where_idis the shard key. - Synchronous driver only; there is no reactive API.
- Spring Boot 4 and Spring Data MongoDB 2025.1; older Spring versions aren't supported.
- MongoDB 5.0 or later.