MongoDB

suggest change

MongoDB is a document database: instead of rows in tables it stores BSON documents (a binary, typed superset of JSON) in collections. A document can contain nested documents and arrays, and two documents in the same collection don't have to share a schema. That makes it a natural fit for data that is shaped like objects, such as product catalogs, user profiles, events and content.

The official Java client is the MongoDB Java Driver. It comes in two flavours: mongodb-driver-sync (blocking, covered here) and mongodb-driver-reactivestreams (a Reactive Streams Publisher API). Spring Data MongoDB and other frameworks are built on top of these drivers.

Add the driver to pom.xml:

<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongodb-driver-sync</artifactId>
    <version>5.13.0</version>
</dependency>

With Gradle: implementation("org.mongodb:mongodb-driver-sync:5.13.0").

This pulls in mongodb-driver-core, bson and bson-record-codec. The driver logs through SLF4J. If no SLF4J binding is on the classpath it prints a one-time warning ("SLF4J not found on the classpath") and disables logging, so add slf4j-simple or Logback to see driver logs.

The examples below were run with JDK 25 against MongoDB 8.0 running as a single-node replica set (needed for transactions), using a database named shop. They build on each other, so run them in the order shown.

Connecting

MongoClients.create() takes a connection string and returns a MongoClient. The client owns a connection pool and monitors the servers in the background. It is thread-safe and expensive to create, so create one client per application, share it, and close it on shutdown.

Databases and collections are created lazily: getDatabase("shop") doesn't talk to the server, and a collection appears when you first insert into it.

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;

public class Connect {
    public static void main(String[] args) {
        String uri = "mongodb://localhost:27017";
        try (MongoClient client = MongoClients.create(uri)) {
            MongoDatabase admin = client.getDatabase("admin");
            Document ping = admin.runCommand(new Document("ping", 1));
            System.out.println("ping: " + ping.get("ok"));

            Document info = admin.runCommand(new Document("buildInfo", 1));
            System.out.println("server version: " + info.getString("version"));

            for (String name : client.listDatabaseNames()) {
                System.out.println("database: " + name);
            }
        }
    }
}

Output:

ping: 1.0
server version: 8.0.4
database: admin
database: config
database: local

runCommand sends any database command as a Document. ping is a cheap way to check that the server is reachable at startup.

Connection strings and settings

Connection strings look like mongodb://user:password@host1:27017,host2:27017/?replicaSet=rs0&authSource=admin or, for MongoDB Atlas, mongodb+srv://user:password@cluster0.example.mongodb.net/. Keep credentials out of source code, for example by reading the string from an environment variable.

For finer control, build MongoClientSettings. Values from the connection string are applied first, and the builder methods after it override them:

import com.mongodb.ConnectionString;
import com.mongodb.MongoClientSettings;
import com.mongodb.ReadPreference;
import com.mongodb.WriteConcern;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;

import java.util.concurrent.TimeUnit;

public class Settings {
    public static void main(String[] args) {
        MongoClientSettings settings = MongoClientSettings.builder()
                .applyConnectionString(new ConnectionString("mongodb://localhost:27017"))
                .applicationName("shop-service")
                .applyToConnectionPoolSettings(pool -> pool
                        .maxSize(50)
                        .minSize(5)
                        .maxConnectionIdleTime(60, TimeUnit.SECONDS))
                .applyToClusterSettings(cluster -> cluster
                        .serverSelectionTimeout(5, TimeUnit.SECONDS))
                .applyToSocketSettings(socket -> socket
                        .connectTimeout(3, TimeUnit.SECONDS))
                .writeConcern(WriteConcern.MAJORITY)
                .readPreference(ReadPreference.primaryPreferred())
                .build();

        try (MongoClient client = MongoClients.create(settings)) {
            System.out.println("pool max size: "
                    + settings.getConnectionPoolSettings().getMaxSize());
            System.out.println("write concern: " + settings.getWriteConcern());
            System.out.println("collections in shop: "
                    + client.getDatabase("shop").listCollectionNames().into(new java.util.ArrayList<>()));
        }
    }
}

Output:

pool max size: 50
write concern: WriteConcern{w=majority, wTimeout=null ms, journal=null}
collections in shop: []

The driver fails fast only if you tell it to. By default, an operation waits up to 30 seconds (serverSelectionTimeout) for a suitable server before throwing MongoTimeoutException. Lowering it to a few seconds makes outages visible quickly instead of hanging request threads.

Documents and inserting data

org.bson.Document is a Map<String, Object> that preserves insertion order. Values can be strings, numbers, booleans, Date, ObjectId, Decimal128, lists and nested Documents.

Every document needs a unique _id. If you don't set one, the driver generates an ObjectId (12 bytes: a timestamp, a random value and a counter) and adds it to your Document before sending it.

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.result.InsertManyResult;
import com.mongodb.client.result.InsertOneResult;
import org.bson.Document;
import org.bson.types.Decimal128;
import org.bson.types.ObjectId;

import java.math.BigDecimal;
import java.time.Instant;
import java.util.Date;
import java.util.List;

public class Insert {
    public static void main(String[] args) {
        try (MongoClient client = MongoClients.create("mongodb://localhost:27017")) {
            MongoCollection<Document> products = client.getDatabase("shop").getCollection("products");
            products.drop(); // start from an empty collection

            Document keyboard = new Document("sku", "KB-01")
                    .append("name", "Mechanical keyboard")
                    .append("price", new Decimal128(new BigDecimal("89.99")))
                    .append("stock", 12)
                    .append("tags", List.of("peripherals", "usb"))
                    .append("specs", new Document("layout", "ANSI").append("switches", "brown"))
                    .append("addedAt", Date.from(Instant.parse("2026-03-01T10:00:00Z")));

            InsertOneResult one = products.insertOne(keyboard);
            ObjectId id = one.getInsertedId().asObjectId().getValue();
            System.out.println("inserted id: " + id.toHexString().length() + " hex chars");
            System.out.println("_id added to document: " + keyboard.containsKey("_id"));

            InsertManyResult many = products.insertMany(List.of(
                    new Document("sku", "MS-02").append("name", "Wireless mouse")
                            .append("price", new Decimal128(new BigDecimal("24.50")))
                            .append("stock", 40).append("tags", List.of("peripherals", "wireless")),
                    new Document("sku", "MN-27").append("name", "27-inch monitor")
                            .append("price", new Decimal128(new BigDecimal("279.00")))
                            .append("stock", 0).append("tags", List.of("displays")),
                    new Document("sku", "HS-05").append("name", "USB headset")
                            .append("price", new Decimal128(new BigDecimal("59.00")))
                            .append("stock", 7).append("tags", List.of("audio", "usb")),
                    new Document("sku", "CB-10").append("name", "USB-C cable")
                            .append("price", new Decimal128(new BigDecimal("9.99")))
                            .append("stock", 150).append("tags", List.of("cables", "usb"))));
            System.out.println("inserted " + many.getInsertedIds().size() + " more");
            System.out.println("count: " + products.countDocuments());

            Document first = products.find().first();
            first.remove("_id");
            System.out.println(first.toJson());
        }
    }
}

Output:

inserted id: 24 hex chars
_id added to document: true
inserted 4 more
count: 5
{"sku": "KB-01", "name": "Mechanical keyboard", "price": {"$numberDecimal": "89.99"}, "stock": 12, "tags": ["peripherals", "usb"], "specs": {"layout": "ANSI", "switches": "brown"}, "addedAt": {"$date": "2026-03-01T10:00:00Z"}}

A few things to note:

Querying

find(filter) returns a FindIterable, a lazy query builder. Nothing is sent to the server until you iterate it or call first(), into() or forEach(). Filters are built with the static helpers in com.mongodb.client.model.Filters, which produce the same JSON query language you'd type in the shell:

import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.bson.types.Decimal128;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import static com.mongodb.client.model.Filters.*;
import static com.mongodb.client.model.Projections.*;
import static com.mongodb.client.model.Sorts.*;

public class Query {
    public static void main(String[] args) {
        try (MongoClient client = MongoClients.create("mongodb://localhost:27017")) {
            MongoCollection<Document> products = client.getDatabase("shop").getCollection("products");

            // Single document by exact match
            Document kb = products.find(eq("sku", "KB-01")).first();
            System.out.println("by sku: " + kb.getString("name"));

            // Missing documents give null, not an exception
            System.out.println("missing: " + products.find(eq("sku", "NOPE")).first());

            // Combined conditions, projection, sort and limit
            Bson inStockUsb = and(eq("tags", "usb"), gt("stock", 0));
            FindIterable<Document> cheapUsb = products.find(inStockUsb)
                    .projection(fields(include("sku", "price"), excludeId()))
                    .sort(ascending("price"))
                    .limit(2);
            for (Document d : cheapUsb) {
                System.out.println("usb: " + d.toJson());
            }

            // Range on a Decimal128 field, collected into a list
            List<String> mid = products.find(and(
                            gte("price", new Decimal128(new BigDecimal("20"))),
                            lt("price", new Decimal128(new BigDecimal("100")))))
                    .sort(descending("price"))
                    .map(d -> d.getString("sku"))
                    .into(new ArrayList<>());
            System.out.println("20..100: " + mid);

            // Other operators: in, regex, nested fields, exists
            System.out.println("in: " + products.countDocuments(in("sku", "KB-01", "MN-27", "XX-00")));
            System.out.println("regex: " + products.countDocuments(regex("name", "^usb", "i")));
            System.out.println("nested: " + products.countDocuments(eq("specs.switches", "brown")));
            System.out.println("has specs: " + products.countDocuments(exists("specs")));

            // Explicit cursor; close it if you stop iterating early
            try (MongoCursor<Document> cursor = products.find(eq("stock", 0)).iterator()) {
                while (cursor.hasNext()) {
                    System.out.println("sold out: " + cursor.next().getString("name"));
                }
            }

            // Reading typed values out of a Document
            int stock = kb.getInteger("stock");
            BigDecimal price = kb.get("price", Decimal128.class).bigDecimalValue();
            List<String> tags = kb.getList("tags", String.class);
            String layout = kb.getEmbedded(List.of("specs", "layout"), String.class);
            System.out.println(stock + " " + price + " " + tags + " " + layout);
        }
    }
}

Output:

by sku: Mechanical keyboard
missing: null
usb: {"sku": "CB-10", "price": {"$numberDecimal": "9.99"}}
usb: {"sku": "HS-05", "price": {"$numberDecimal": "59.00"}}
20..100: [KB-01, HS-05, MS-02]
in: 2
regex: 2
nested: 1
has specs: 1
sold out: 27-inch monitor
12 89.99 [peripherals, usb] ANSI

To run a filter written as JSON, for example one loaded from a configuration file, use Document.parse("{\"stock\": {\"$gt\": 0}}"). Never build such strings by concatenating user input.

Updating

Update operators modify individual fields on the server, without reading the document first. The helpers live in com.mongodb.client.model.Updates:

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.FindOneAndUpdateOptions;
import com.mongodb.client.model.ReturnDocument;
import com.mongodb.client.model.UpdateOptions;
import com.mongodb.client.result.UpdateResult;
import org.bson.Document;

import static com.mongodb.client.model.Filters.*;
import static com.mongodb.client.model.Updates.*;

public class Update {
    public static void main(String[] args) {
        try (MongoClient client = MongoClients.create("mongodb://localhost:27017")) {
            MongoCollection<Document> products = client.getDatabase("shop").getCollection("products");

            // Modify fields of one document
            UpdateResult r = products.updateOne(eq("sku", "MS-02"),
                    combine(set("name", "Wireless mouse (2026)"), inc("stock", -1), addToSet("tags", "sale")));
            System.out.println("matched=" + r.getMatchedCount() + " modified=" + r.getModifiedCount());

            // Update many documents at once
            r = products.updateMany(eq("tags", "usb"), push("tags", "featured"));
            System.out.println("usb products tagged: " + r.getModifiedCount());

            // Upsert: insert if nothing matches
            r = products.updateOne(eq("sku", "WC-01"),
                    combine(set("name", "Webcam"), setOnInsert("stock", 0)),
                    new UpdateOptions().upsert(true));
            System.out.println("upserted id present: " + (r.getUpsertedId() != null));

            // Atomically decrement stock only if available, and get the new document
            Document after = products.findOneAndUpdate(
                    and(eq("sku", "HS-05"), gt("stock", 0)),
                    inc("stock", -1),
                    new FindOneAndUpdateOptions().returnDocument(ReturnDocument.AFTER));
            System.out.println("HS-05 stock now: " + after.getInteger("stock"));

            // Same call on a sold-out product matches nothing and returns null
            Document soldOut = products.findOneAndUpdate(
                    and(eq("sku", "MN-27"), gt("stock", 0)), inc("stock", -1));
            System.out.println("MN-27 reserved: " + (soldOut != null));

            // Replace the whole document (except _id)
            r = products.replaceOne(eq("sku", "WC-01"),
                    new Document("sku", "WC-01").append("name", "HD webcam").append("stock", 3));
            System.out.println("replaced: " + r.getModifiedCount());

            Document ms = products.find(eq("sku", "MS-02")).first();
            System.out.println(ms.getString("name") + " " + ms.getInteger("stock") + " " + ms.getList("tags", String.class));
        }
    }
}

Output:

matched=1 modified=1
usb products tagged: 3
upserted id present: true
HS-05 stock now: 6
MN-27 reserved: false
replaced: 1
Wireless mouse (2026) 39 [peripherals, wireless, sale]

Deleting

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.result.DeleteResult;
import org.bson.Document;

import static com.mongodb.client.model.Filters.*;

public class Delete {
    public static void main(String[] args) {
        try (MongoClient client = MongoClients.create("mongodb://localhost:27017")) {
            MongoCollection<Document> products = client.getDatabase("shop").getCollection("products");

            DeleteResult r = products.deleteOne(eq("sku", "WC-01"));
            System.out.println("deleted one: " + r.getDeletedCount());

            Document removed = products.findOneAndDelete(eq("sku", "MN-27"));
            System.out.println("removed: " + removed.getString("name"));

            r = products.deleteMany(lt("stock", 0));
            System.out.println("deleted negative stock: " + r.getDeletedCount());
            System.out.println("remaining: " + products.countDocuments());
        }
    }
}

Output:

deleted one: 1
removed: 27-inch monitor
deleted negative stock: 0
remaining: 4

collection.drop() removes the collection together with its indexes, which is much faster than deleteMany(new Document()).

Mapping to Java records and POJOs

Working with Document and string keys gets tedious. The driver can encode and decode Java records directly: pass the class to getCollection() and you get a MongoCollection<Customer>. Record support is in the default codec registry, so no extra configuration is needed.

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import org.bson.codecs.pojo.annotations.BsonId;
import org.bson.codecs.pojo.annotations.BsonProperty;
import org.bson.types.ObjectId;

import java.math.BigDecimal;
import java.time.Instant;
import java.util.List;

import static com.mongodb.client.model.Filters.*;
import static com.mongodb.client.model.Sorts.*;
import static com.mongodb.client.model.Updates.*;

public class Records {
    public record Address(String city, String zip) {}

    public record Customer(
            @BsonId ObjectId id,
            String name,
            @BsonProperty("email_address") String email,
            BigDecimal credit,
            List<String> roles,
            Address address,
            Instant createdAt) {}

    public static void main(String[] args) {
        try (MongoClient client = MongoClients.create("mongodb://localhost:27017")) {
            MongoCollection<Customer> customers = client.getDatabase("shop")
                    .getCollection("customers", Customer.class);
            customers.drop();

            customers.insertMany(List.of(
                    new Customer(new ObjectId(), "Alice", "alice@example.com", new BigDecimal("150.00"),
                            List.of("admin"), new Address("Berlin", "10115"),
                            Instant.parse("2026-01-15T09:30:00Z")),
                    new Customer(new ObjectId(), "Bob", "bob@example.com", new BigDecimal("20.50"),
                            List.of(), new Address("Paris", "75001"),
                            Instant.parse("2026-02-20T14:00:00Z"))));

            // Filters use the stored field names
            Customer alice = customers.find(eq("email_address", "alice@example.com")).first();
            System.out.println(alice.name() + " lives in " + alice.address().city()
                    + ", credit " + alice.credit());

            customers.updateOne(eq("_id", alice.id()), push("roles", "support"));
            for (Customer c : customers.find(eq("address.city", "Berlin")).sort(ascending("name"))) {
                System.out.println(c.name() + " " + c.roles() + " since " + c.createdAt());
            }

            // The same collection is still readable as raw documents
            org.bson.Document raw = client.getDatabase("shop").getCollection("customers")
                    .find(eq("name", "Bob")).first();
            raw.remove("_id");
            System.out.println(raw.toJson());
        }
    }
}

Output:

Alice lives in Berlin, credit 150.00
Alice [admin, support] since 2026-01-15T09:30:00Z
{"name": "Bob", "email_address": "bob@example.com", "credit": {"$numberDecimal": "20.50"}, "roles": [], "address": {"city": "Paris", "zip": "75001"}, "createdAt": {"$date": "2026-02-20T14:00:00Z"}}

Indexes

Without an index, a query scans every document in the collection. Create indexes for the fields you filter and sort by. createIndex is idempotent: calling it for an index that already exists does nothing, so it's common to run it at application startup.

import com.mongodb.ErrorCategory;
import com.mongodb.MongoWriteException;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.IndexOptions;
import com.mongodb.client.model.Indexes;
import com.mongodb.client.model.Sorts;
import org.bson.Document;

import java.util.concurrent.TimeUnit;

import static com.mongodb.client.model.Filters.*;

public class IndexDemo {
    public static void main(String[] args) {
        try (MongoClient client = MongoClients.create("mongodb://localhost:27017")) {
            MongoCollection<Document> products = client.getDatabase("shop").getCollection("products");

            // Unique index: the database enforces that no two products share a sku
            products.createIndex(Indexes.ascending("sku"), new IndexOptions().unique(true).name("sku_unique"));

            // Compound index supporting "filter by tag, sort by price"
            products.createIndex(Indexes.compoundIndex(Indexes.ascending("tags"), Indexes.ascending("price")));

            // TTL index: documents expire 30 days after createdAt
            client.getDatabase("shop").getCollection("sessions")
                    .createIndex(Indexes.ascending("createdAt"), new IndexOptions().expireAfter(30L, TimeUnit.DAYS));

            for (Document ix : products.listIndexes()) {
                System.out.println(ix.getString("name") + " " + ix.get("key", Document.class).toJson());
            }

            try {
                products.insertOne(new Document("sku", "KB-01").append("name", "Duplicate"));
            } catch (MongoWriteException e) {
                if (e.getError().getCategory() == ErrorCategory.DUPLICATE_KEY) {
                    System.out.println("duplicate sku rejected, code " + e.getError().getCode());
                }
            }

            // explain() shows whether a query uses an index
            Document plan = products.find(eq("tags", "usb")).sort(Sorts.ascending("price")).explain();
            Document winning = plan.get("queryPlanner", Document.class).get("winningPlan", Document.class);
            System.out.println("uses index: " + winning.toJson().contains("IXSCAN"));
        }
    }
}

Output:

_id_ {"_id": 1}
sku_unique {"sku": 1}
tags_1_price_1 {"tags": 1, "price": 1}
duplicate sku rejected, code 11000
uses index: true

Aggregation

The aggregation pipeline is MongoDB's equivalent of GROUP BY, JOIN and computed columns. A pipeline is a list of stages, and each stage transforms the stream of documents. The Aggregates and Accumulators helpers build the stages:

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import org.bson.Document;
import org.bson.types.Decimal128;

import java.math.BigDecimal;
import java.util.List;

import static com.mongodb.client.model.Accumulators.*;
import static com.mongodb.client.model.Aggregates.*;
import static com.mongodb.client.model.Filters.*;
import static com.mongodb.client.model.Projections.*;
import static com.mongodb.client.model.Sorts.*;

public class Aggregate {
    static Document order(String customer, String status, String... items) {
        List<Document> lines = new java.util.ArrayList<>();
        for (int i = 0; i < items.length; i += 3) {
            lines.add(new Document("sku", items[i])
                    .append("qty", Integer.parseInt(items[i + 1]))
                    .append("price", new Decimal128(new BigDecimal(items[i + 2]))));
        }
        return new Document("customer", customer).append("status", status).append("items", lines);
    }

    public static void main(String[] args) {
        try (MongoClient client = MongoClients.create("mongodb://localhost:27017")) {
            MongoCollection<Document> orders = client.getDatabase("shop").getCollection("orders");
            orders.drop();
            orders.insertMany(List.of(
                    order("alice", "paid", "KB-01", "1", "89.99", "CB-10", "3", "9.99"),
                    order("bob", "paid", "MS-02", "2", "24.50"),
                    order("alice", "paid", "HS-05", "1", "59.00"),
                    order("carol", "cancelled", "KB-01", "1", "89.99"),
                    order("bob", "paid", "CB-10", "5", "9.99")));

            // Revenue per customer from paid orders
            List<Document> perCustomer = orders.aggregate(List.of(
                    match(eq("status", "paid")),
                    unwind("$items"),
                    group("$customer",
                            sum("revenue", new Document("$multiply", List.of("$items.qty", "$items.price"))),
                            sum("units", "$items.qty"),
                            addToSet("skus", "$items.sku")),
                    sort(descending("revenue")))).into(new java.util.ArrayList<>());
            for (Document d : perCustomer) {
                System.out.println(d.toJson());
            }

            // Best-selling products, joined with the products collection
            orders.aggregate(List.of(
                    match(eq("status", "paid")),
                    unwind("$items"),
                    group("$items.sku", sum("units", "$items.qty")),
                    sort(descending("units")),
                    limit(2),
                    lookup("products", "_id", "sku", "product"),
                    project(fields(
                            computed("name", new Document("$first", "$product.name")),
                            include("units")))))
                    .forEach(d -> System.out.println(d.getString("_id") + " "
                            + d.getString("name") + " x" + d.getInteger("units")));
        }
    }
}

Output:

{"_id": "alice", "revenue": {"$numberDecimal": "178.96"}, "units": 5, "skus": ["CB-10", "KB-01", "HS-05"]}
{"_id": "bob", "revenue": {"$numberDecimal": "98.95"}, "units": 7, "skus": ["CB-10", "MS-02"]}
CB-10 USB-C cable x8
MS-02 Wireless mouse (2026) x2

Transactions

A single-document write is always atomic. When you need to change several documents or collections all-or-nothing, use a multi-document transaction. Transactions require a replica set or sharded cluster; a standalone mongod rejects them. For local development, start mongod --replSet rs0 and run rs.initiate() once in mongosh.

ClientSession.withTransaction() starts a transaction, runs your callback, and commits. If the callback throws, it aborts and rethrows. It also retries automatically on transient errors such as write conflicts, so the callback must be safe to run more than once. Every operation inside it must receive the session argument, or it runs outside the transaction:

import com.mongodb.client.ClientSession;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import org.bson.Document;

import java.util.List;

import static com.mongodb.client.model.Filters.*;
import static com.mongodb.client.model.Updates.*;

public class PlaceOrder {
    static void placeOrder(MongoClient client, String sku, int qty) {
        MongoCollection<Document> products = client.getDatabase("shop").getCollection("products");
        MongoCollection<Document> orders = client.getDatabase("shop").getCollection("orders");

        try (ClientSession session = client.startSession()) {
            String orderId = session.withTransaction(() -> {
                Document p = products.findOneAndUpdate(session,
                        and(eq("sku", sku), gte("stock", qty)), inc("stock", -qty));
                if (p == null) {
                    throw new IllegalStateException("not enough stock for " + sku);
                }
                Document order = new Document("customer", "dave").append("status", "paid")
                        .append("items", List.of(new Document("sku", sku).append("qty", qty)
                                .append("price", p.get("price"))));
                orders.insertOne(session, order);
                return order.getObjectId("_id").toHexString();
            });
            System.out.println("order placed for " + qty + " x " + sku + " (id length " + orderId.length() + ")");
        } catch (IllegalStateException e) {
            System.out.println("rolled back: " + e.getMessage());
        }
    }

    public static void main(String[] args) {
        try (MongoClient client = MongoClients.create("mongodb://localhost:27017")) {
            MongoCollection<Document> products = client.getDatabase("shop").getCollection("products");
            MongoCollection<Document> orders = client.getDatabase("shop").getCollection("orders");

            placeOrder(client, "HS-05", 2);
            placeOrder(client, "HS-05", 100);

            System.out.println("HS-05 stock: " + products.find(eq("sku", "HS-05")).first().getInteger("stock"));
            System.out.println("dave's orders: " + orders.countDocuments(eq("customer", "dave")));
        }
    }
}

Output:

order placed for 2 x HS-05 (id length 24)
rolled back: not enough stock for HS-05
HS-05 stock: 4
dave's orders: 1

The second order fails the stock check, the exception aborts the transaction, and neither collection changes. Keep transactions short (by default the server aborts them after 60 seconds) and prefer designing documents so that data that changes together lives in one document, which needs no transaction at all.

Bulk writes

bulkWrite sends many inserts, updates and deletes in as few round-trips as possible. By default operations are ordered: they run in sequence and stop at the first error. With ordered(false) the server may run them in any order and continues past errors:

import com.mongodb.MongoBulkWriteException;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.BulkWriteOptions;
import com.mongodb.client.model.DeleteOneModel;
import com.mongodb.client.model.InsertOneModel;
import com.mongodb.client.model.UpdateOneModel;
import com.mongodb.client.model.UpdateOptions;
import com.mongodb.client.model.WriteModel;
import com.mongodb.bulk.BulkWriteResult;
import org.bson.Document;

import java.util.List;

import static com.mongodb.client.model.Filters.*;
import static com.mongodb.client.model.Updates.*;

public class Bulk {
    public static void main(String[] args) {
        try (MongoClient client = MongoClients.create("mongodb://localhost:27017")) {
            MongoCollection<Document> products = client.getDatabase("shop").getCollection("products");

            List<WriteModel<Document>> ops = List.of(
                    new InsertOneModel<>(new Document("sku", "SP-01").append("name", "Speakers").append("stock", 4)),
                    new UpdateOneModel<>(eq("sku", "CB-10"), inc("stock", 50)),
                    new UpdateOneModel<>(eq("sku", "PD-01"), set("name", "Mouse pad"),
                            new UpdateOptions().upsert(true)),
                    new DeleteOneModel<>(eq("sku", "SP-01")));

            BulkWriteResult r = products.bulkWrite(ops);
            System.out.println("inserted=" + r.getInsertedCount() + " modified=" + r.getModifiedCount()
                    + " upserted=" + r.getUpserts().size() + " deleted=" + r.getDeletedCount());

            // Unordered: keep going after an error, then report all failures
            try {
                products.bulkWrite(List.of(
                        new InsertOneModel<>(new Document("sku", "KB-01")),   // duplicate
                        new InsertOneModel<>(new Document("sku", "LT-01").append("name", "Desk lamp")),
                        new InsertOneModel<>(new Document("sku", "MS-02"))),  // duplicate
                        new BulkWriteOptions().ordered(false));
            } catch (MongoBulkWriteException e) {
                System.out.println("inserted despite errors: " + e.getWriteResult().getInsertedCount());
                e.getWriteErrors().forEach(err ->
                        System.out.println("op #" + err.getIndex() + " failed with code " + err.getCode()));
            }
        }
    }
}

Output:

inserted=1 modified=1 upserted=1 deleted=1
inserted despite errors: 1
op #0 failed with code 11000
op #2 failed with code 11000

MongoBulkWriteException.getWriteErrors() tells you exactly which operations failed (by index in your list) and why, while getWriteResult() reports what did succeed.

Best practices

For relational databases, see JDBC and PostgreSQL. For caching in front of a database, see Redis.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents