Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 66 ยท Data Access

Spring Data MongoDB, Redis and Other Stores

Learn when a document or key-value store beats SQL, how Spring Data MongoDB repositories and Redis templates work, and how to choose a data store in Spring Boot.

Everything so far in this chapter assumed a relational database, and for most business applications that is the right default: transactions, joins, constraints and decades of tooling. But some data does not fit neatly into tables and rows. A product catalog where every category has different attributes, an event log with a changing shape, a session token that should vanish after thirty minutes, a counter updated thousands of times a second. For these, a non-relational (NoSQL) store can be simpler, faster, or both.

Spring Data gives every store the same programming model: a repository interface for the common cases and a template class for everything else. If you know Spring Data JPA repositories, the MongoDB version will feel familiar. This lesson explains when to leave SQL, how MongoDB repositories and Redis templates look in Boot, and how to choose.

MongoDB and Redis servers cannot run on this site, so the Spring code is read-only. The runnable examples are stand-ins: an in-memory document repository whose query methods are derived from method names, using real Jackson to turn Java records into documents, and a small Redis-like store with expiry, counters and rankings.

Four families of stores

Relational Tables, joins, transactions. The default.
Document JSON-like records. MongoDB.
Key-value Fast lookup by key. Redis.
Search Ranking and full text. Elasticsearch, Meilisearch.
1 / 2

When a document store fits

A document database stores each record as a JSON-like document, usually with nested objects and arrays, and finds documents by their fields. MongoDB is the best-known one. Its strengths are a flexible schema, nested data that is read together, and horizontal scaling.

A relational model would split an order across three tables (orders, order_lines, addresses) and join them for every read. In MongoDB the same order is one document:

JSON
{
  "_id": "o-1001",
  "status": "PAID",
  "customer": { "name": "Ada", "city": "London" },
  "lines": [
    { "sku": "KB-1", "quantity": 1, "unitPrice": 79.0 },
    { "sku": "MS-7", "quantity": 2, "unitPrice": 25.5 }
  ]
}

One read returns everything the order page needs. Good candidates are catalogs with varying attributes, content management, event and audit logs, and user profiles. Poor candidates are data with many relationships between independent records, strict multi-row consistency (account balances), or heavy ad-hoc reporting with joins. MongoDB does support multi-document transactions, but only on a replica set, and they are the exception rather than the design.

"Schemaless" does not mean "no schema". Your code still expects fields to exist and have types. The schema just lives in your Java classes (and validation rules) instead of in create table statements. Plan migrations for documents too: old documents stay in the old shape until you rewrite them.

Spring Data MongoDB in Boot

Add the starter and point it at a server:

XML
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
YAML
spring:
  data:
    mongodb:
      uri: mongodb://localhost:27017/shop

Property names for the connection changed between Boot generations (Spring Boot 4 introduced a spring.mongodb prefix), so check the reference of your version. Boot creates the client and a MongoTemplate for you. Map a class with @Document:

Java
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = "orders")
public class Order {
    @Id
    private String id;
    @Indexed
    private String status;
    private Customer customer;          // embedded object
    private List<OrderLine> lines;      // embedded array
    // constructors, getters
}

public record Customer(String name, String city) { }
public record OrderLine(String sku, int quantity, double unitPrice) { }

@Id maps to MongoDB's _id; a String id is generated as an ObjectId when null. Embedded objects need no annotation: they become nested documents. Unlike JPA there is no lazy loading and no N+1 problem for embedded data, because it all arrives in one document.

Repositories

Java
public interface OrderRepository extends MongoRepository<Order, String> {

    List<Order> findByStatus(String status);

    List<Order> findByCustomerCity(String city);          // nested field customer.city

    long countByStatus(String status);

    @Query("{ 'lines.sku': ?0, 'status': 'PAID' }")
    List<Order> paidOrdersContaining(String sku);
}

Method names are parsed exactly as in JPA, and findByCustomerCity traverses into the embedded object. @Query takes a JSON filter with ?0 placeholders for parameters. You get save, findById, findAll(Pageable), deleteById and the rest for free.

MongoTemplate for everything else

Aggregations, partial updates and dynamic filters go through the template:

Java
@Service
public class OrderReports {

    private final MongoTemplate mongo;

    public OrderReports(MongoTemplate mongo) {
        this.mongo = mongo;
    }

    public void markShipped(String id) {
        mongo.updateFirst(
                Query.query(Criteria.where("id").is(id)),
                new Update().set("status", "SHIPPED"),
                Order.class);
    }
}

updateFirst changes one field on the server without loading and re-saving the whole document, which is both faster and safer under concurrent writes.

Things to know in production

  • Indexes. Spring Data MongoDB does not create indexes from @Indexed by default; set spring.data.mongodb.auto-index-creation: true for development, and manage indexes deliberately (scripts or a migration tool) in production. Without an index, a query scans every document.
  • Document size. One document is limited to 16 MB, and an array that grows without bound (every click ever made by a user) is a design smell. Embed what is bounded, reference what is not.
  • References. For related data that changes independently, store the other document's id (or use @DocumentReference) and load it with a second query. There are no server-side foreign keys.
  • Consistency. Writes to one document are atomic. Anything across documents needs a transaction (replica set) or a design that tolerates temporary inconsistency.

A document repository you can run

How does findByCustomerCity become a query? Spring Data creates a proxy for your interface and, for each method, parses the name: a prefix such as findBy or countBy, then the property path. The stand-in below does the same over an in-memory list of documents. Jackson (a real dependency in this runner) converts Java records into nested maps, which is exactly what a document mapper does with your entities. The query part is simplified: equality on one property path.

Java Derived queries over documents

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

What is real: the proxy-plus-method-name technique, and records becoming nested documents. What is the stand-in: Spring Data builds real MongoDB queries (with operators, sorting, paging, projections and index use), maps documents back to your entity type and supports @Query, aggregation and change tracking.

Redis: more than a cache

Redis is an in-memory data structure server. Every value lives under a key, and values can be strings, hashes, lists, sets, or sorted sets. Operations are atomic and extremely fast, and any key can expire. You already saw it as a cache provider in Caching; it is also a good home for:

  • Sessions and tokens that must disappear automatically (SET key value EX 1800).
  • Counters and rate limits (INCR is atomic, so a thousand threads can count safely).
  • Leaderboards (sorted sets keep members ordered by score).
  • Short-lived locks, queues and pub/sub messages.

Redis is usually not the system of record: data lives in memory, and persistence options exist (snapshots, append-only files) but are a trade-off. Treat it as fast, valuable, and rebuildable.

Templates in Boot

XML
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
YAML
spring:
  data:
    redis:
      host: localhost
      port: 6379

Boot (using the Lettuce client by default) provides a StringRedisTemplate and a RedisTemplate<Object, Object>:

Java
@Service
public class LoginAttempts {

    private final StringRedisTemplate redis;

    public LoginAttempts(StringRedisTemplate redis) {
        this.redis = redis;
    }

    public boolean isBlocked(String user) {
        String key = "login:attempts:" + user;
        Long attempts = redis.opsForValue().increment(key);
        if (attempts != null && attempts == 1) {
            redis.expire(key, Duration.ofMinutes(15));   // window starts at the first attempt
        }
        return attempts != null && attempts > 5;
    }

    public void saveSession(String token, String userId) {
        redis.opsForValue().set("session:" + token, userId, Duration.ofMinutes(30));
    }

    public void addScore(String player, double points) {
        redis.opsForZSet().incrementScore("leaderboard", player, points);
    }
}

opsForValue(), opsForHash(), opsForList(), opsForSet() and opsForZSet() map to the Redis data types. Prefer StringRedisTemplate for simple text and use a JSON serializer for objects. The default RedisTemplate uses Java serialization, which stores unreadable bytes and breaks when classes change. There is also a repository style (@RedisHash with CrudRepository) for storing small entities as hashes, convenient for sessions, but you give up most of Redis's strengths when you treat it like a table. A deeper tour of the client and data types is in Spring Data Redis.

The second stand-in is a minimal Redis-like store with a fake clock. It shows the three ideas above: expiry, an atomic counter with a time window, and a sorted set.

Java A tiny Redis-like store

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

What is real: the data-type ideas (value with TTL, atomic increment, sorted set), and the same window-starts-at-first-attempt rate limit as in the Spring code. What is the stand-in: real Redis is a networked server with persistence, replication, clustering, many more commands (including scripts for multi-step atomic operations) and sub-millisecond performance for millions of keys. In the stand-in, increment is only "atomic" because the example is single-threaded.

Choosing a store

Ask what the data looks like and how it is read, not what is fashionable:

Need Reasonable choice
Orders, accounts, invoices, anything with joins and constraints Relational (PostgreSQL, MySQL)
Records with varying shape, read as a whole Document store (MongoDB), or JSON columns in PostgreSQL
Cache, sessions, counters, rate limits, leaderboards Redis
Full-text search with ranking and typo tolerance A search engine (Elasticsearch, OpenSearch, Meilisearch)
Huge write volume of time-ordered data A time-series or wide-column store
Messages between services A broker such as Kafka or RabbitMQ (a later lesson)

Practical rules:

  1. Start with one relational database. Modern PostgreSQL stores JSON, searches text and handles many workloads. Add a second store when you can name the specific problem it solves.
  2. One source of truth. Pick one store as the owner of each piece of data; others hold copies that can be rebuilt (a search index, a cache).
  3. Count the operational cost. Every store needs backups, monitoring, upgrades, security and people who understand it.
  4. Keep the access behind an interface. A service that depends on OrderRepository can be tested without the real database, and swapping a store later hurts less.

Spring Boot can run several stores at once without conflict: each starter configures its own client, and repositories are routed to the store whose module they extend. If you put JPA and MongoDB in one project, use @EnableJpaRepositories and @EnableMongoRepositories on the right packages so each scan finds only its own repositories.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which data is a good fit for a document store such as MongoDB?

    Varying structure that is read together suits a document. Heavily related or strictly transactional data usually stays relational.
  2. 2. How does Spring Data turn findByCustomerCity(String city) into a query?

    Both JPA and MongoDB repositories derive queries from the method name; nested property paths traverse into embedded objects.
  3. 3. Why is the default RedisTemplate serialization a poor choice for most apps?

    Use StringRedisTemplate for text, or configure a JSON serializer, so keys and values stay readable and evolvable.
  4. 4. A login throttle should allow 5 attempts in 15 minutes. Which Redis feature gives you that with the least code?

    INCR is atomic and EXPIRE removes the key when the window ends, so the counter resets by itself.
  5. 5. What is a sensible default when starting a new application's persistence?

    Every extra store adds operations and consistency problems. Add one when you can name the need it solves.

Summary

  • Choose a store by data shape and access pattern; relational stays the default, and extra stores need a named reason.
  • Spring Data MongoDB maps @Document classes, derives repository queries from method names and offers MongoTemplate for updates and aggregations; remember to create indexes deliberately.
  • Documents embed bounded data and reference unbounded or independent data; there are no joins or foreign keys.
  • Redis offers expiring keys, atomic counters, hashes and sorted sets through StringRedisTemplate; treat it as fast and rebuildable, not as your only copy.
  • Keep one source of truth per piece of data, and hide each store behind a repository or service interface.

Next: Spring Security Fundamentals.