diffsert

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:

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:

mongosh
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:

  1. It copies the stored values of preserved fields into the new document.
  2. 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.
  3. If nothing else differs, it keeps the stored document as it is. That is a no-op, even though the ignored fields differ.
  4. Otherwise it writes the result, with the version field incremented if there is one.
  1. Find the stored document by _id
  2. Stored document found? noINSERTED · insert eventwith update: NOT_FOUND, no event
  3. yesCopy back the stored preserved fields
  4. Anything else differs?ignored, version and preserved fields left out noUNCHANGED · no eventthe stored document stays as it is
  5. yesWrite the result, version + 1
  6. MongoDB diffs it against the stored one deltaUPDATED · update eventwith only the changed fields
What one write goes through. The comparison happens only with ignored, preserved or version fields; without them, the server's own diff decides, and an identical document is a no-op as well. For small documents or near-total rewrites, MongoDB logs a 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 resultOutcomeChange event
Inserted by the upsertINSERTEDinsert
Matched and modifiedUPDATEDupdate, sometimes replace (see Change streams)
Matched, not modifiedUNCHANGEDnone
Not matched, no upsertNOT_FOUNDnone

Installation

Diffsert has three modules on Maven Central, under the group id dev.jbaby. Pick one:

ArtifactUse it forBrings in
diffsert-spring-boot-starterA Spring Boot 4 applicationdiffsert-spring-data, Boot's MongoDB starter
diffsert-spring-dataSpring Data MongoDB without Boot's auto-configurationdiffsert-core, Spring Data MongoDB
diffsert-coreThe plain MongoDB Java driver, no Springmongodb-driver-sync
pom.xml
<dependency>
    <groupId>dev.jbaby</groupId>
    <artifactId>diffsert-spring-boot-starter</artifactId>
    <version>0.3.0</version>
</dependency>
build.gradle.kts
implementation("dev.jbaby:diffsert-spring-boot-starter:0.3.0")

Requirements:

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.

application.yml
diffsert:
  ignore-fields: jobRunId, _updatedAt   # alone, these are not a change
  preserve-fields: _createdAt           # the stored value wins once set
CustomerDto.java
@Document("customers")
public record CustomerDto(
        @Id String id,
        String name,
        String city,
        String jobRunId,
        @Field("_createdAt") Instant createdAt,
        @Field("_updatedAt") Instant updatedAt) {
}
CustomerSync.java
@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:

DiffsertConfig.java
@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:

CustomerSync.java
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 methodWhat 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:

FieldMeaning
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:

Change explorer: for each situation, the stored and the new document field by field, the document after the write, the outcome and the change event.

More cases, in replace mode, the default:

StoredNewResult
{ 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.

one write, both modes
// 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:

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:

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.

WriteStored versionEvent
First write0insert
Same data, next run0none
city changed1update: 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:

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.

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:

AnnotationHandled asEffect
@CreatedDate, @CreatedByPreserved fieldSet when the document is inserted, then kept
@LastModifiedDate, @LastModifiedByIgnored fieldWritten only together with a real change

With the Spring Boot starter, @EnableMongoAuditing is all it takes:

Order.java
@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:

DiffsertConfig.java
@Bean
Diffsert diffsert(MongoTemplate mongoTemplate,
        @Qualifier("mongoAuditingHandler") AuditingHandler auditingHandler) {
    return new Diffsert(mongoTemplate).withAuditing(auditingHandler);
}

What happens on a write:

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:

PropertyDefaultMeaning
diffsert.modereplacereplace or merge, see Replace and merge mode
diffsert.ignore-fieldsnoneFields that alone don't count as a change, see Ignored fields
diffsert.preserve-fieldsnoneFields whose stored value is kept, see Preserved fields
diffsert.version-field 0.2.0noneA field that counts real changes, see Version field
diffsert.orderedfalseOrdered bulk writes stop at the first error
diffsert.remove-type-keytrueRemove _class from converted entities
DiffsertConfig.java
@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.

Java
Diffsert logging = diffsert.withListener((collection, result) ->
        log.info("{}: {}", collection, result));
// customers: requested=1000, inserted=3, updated=12, unchanged=985, notFound=0

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:

OrderImport.java
@Transactional
void importOrders(List<Order> orders, List<OrderLine> lines) {
    diffsert.upsertAll(orders, Order.class);
    diffsert.upsertAll(lines, OrderLine.class);
}

Without Spring, or to combine Diffsert's writes with other operations in one bulk write, build the write models and execute them yourself:

Java
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

OutcomeChange event
INSERTEDinsert, with the full document
UPDATEDupdate with updatedFields, removedFields and truncatedArrays; for small documents sometimes replace
UNCHANGEDnone
NOT_FOUNDnone
update event, city changed
{ operationType: "update",
  documentKey: { _id: "c1" },
  updateDescription: {
    updatedFields: { city: "Hamburg", jobRunId: "run-2",
                     _updatedAt: ISODate("2026-10-08T12:00Z") },
    removedFields: [],
    truncatedArrays: [] } }

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:

AddressListener.java
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 modeUpdate event (Diffsert)Replace event
change_streams_update_full (default)updateDescription, plus the full document in afterFull document in after, no updateDescription
change_streamsupdateDescription only, no afterFull document in after, no updateDescription
*_with_pre_image (MongoDB 6.0+)Additionally the old document in beforeAdditionally before

Errors and retries

Rejected before writing

These problems are found before anything is written, and throw an IllegalArgumentException:

Message starts withCause
entity has no id, document has no _idThe id is missing or null.
collection … has an unacknowledged write concernThe 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 supportedThe 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 wellOne field configured twice.
auditing field '…' of … is nestedAn auditing annotation inside an embedded object. 0.2.0
entities in one batch must have the same auditing and version fieldsEntity 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:

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):

CustomerDocuments.java
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);
}

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:

CustomerSync.java
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()

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:

Java
// 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:

Java
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:

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

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

Limitations