Scrivio Interview library
ScenarioAdvanced7 min read · updated 12 November 2026

A large Spring Data MongoDB codebase uses @DBRef everywhere, and loading lists is slow with many extra queries. How would you improve it across the codebase?

@DBRef makes Spring Data MongoDB run an extra query for every referenced document, so a list of 50 orders with a customer reference becomes 51 queries, a classic N+1 pattern. We fix it by storing plain ids and loading related documents in one batch with $in, by using @DocumentReference with an explicit lookup where it fits, by embedding fields that are always shown together, and by using $lookup aggregations for read models, migrating one endpoint at a time with tests that count queries.

Why this question is asked

Slow list pages are one of the most common complaints in Spring Data MongoDB codebases that grew from a relational mindset. Each entity points at others with @DBRef, everything looks neat, and then a page that shows 100 items needs hundreds of round trips to the database. Interviewers ask this as a scenario question because the fix is not one line: it touches the data model, the repositories and the way we test. In this answer, we will recap what @DBRef does, measure the N+1 pattern, look at the replacements and when each fits, and then plan a safe migration across a large codebase.

1A Quick Recap of @DBRef

MongoDB has no joins at the storage level. A DBRef is a convention for storing a pointer to another document: a small sub-document with the target collection name and its id, such as { $ref: "customers", $id: ObjectId("...") }. The database does nothing special with it; it is just data.

Spring Data's @DBRef annotation tells the mapping layer to store a field that way and to resolve it when reading. Resolving means running findById on the referenced collection for each reference. With lazy = true, Spring puts a proxy, a stand-in object generated at runtime, in the field instead, and runs the query the first time any method on it is called. Either way, every reference costs one query.

Java
@Document("orders")
class Order {
@Id String id;
@DBRef Customer customer; // one extra query per order when read
@DBRef List<Product> products; // one extra query per product reference
}

2Measuring the N+1 Pattern

Before changing anything, we measure. Turning on the driver's command logging or the MongoDB profiler on a test database shows every query an endpoint sends. For a list of 50 orders, each with a customer and three products, the count is easy to predict.

Java
List<Order> orders = orderRepository.findByStatus("OPEN"); // 1 query, 50 orders
for (Order o : orders) {
o.getCustomer().getName(); // 50 queries to customers (one per order)
o.getProducts().size(); // 150 queries to products (one per reference)
}
// total: 201 round trips for one page
Step throughLoading a list with @DBRef
Serviceorderscustomers
find orders where status = OPEN
50 orders with DBRefs
findById(customer of order 1)
customer 1
findById(customer of order 2)
customer 2
... 48 more single lookups

7 messages in order. Play them, or step through them one at a time.

Each reference becomes its own round trip; products add 150 more.

Each query may take only a millisecond or two, but 201 round trips add up to hundreds of milliseconds and a lot of load on the server. Lazy loading only moves the cost: the queries happen later, when a JSON serializer touches the proxies, and they are harder to see. So the root problem is resolving references one at a time.

3Fix 1: Store Ids and Load in Batches

The most widely useful fix is to store the referenced id as a plain field and load all related documents in one query with $in. The service decides what to load, and it loads it once per page instead of once per item.

Java
@Document("orders")
record Order(@Id String id, String status, String customerId, List<String> productIds) {}
List<Order> orders = orderRepository.findByStatus("OPEN"); // 1 query
Set<String> ids = orders.stream().map(Order::customerId).collect(toSet());
Map<String, Customer> customers = customerRepository.findAllById(ids) // 1 query with $in
.stream().collect(toMap(Customer::id, c -> c));
// total: 2 queries for customers instead of 51, plus 1 for all products

Notice that this also makes the cost visible in the code. Anyone reading the service sees exactly which queries run. findAllById() sends a single query with _id: { $in: [...] }, which uses the _id index.

Newer versions of Spring Data MongoDB also offer @DocumentReference, which stores just the id (or another field) and lets us define how to look the target up, including lazy loading. It produces cleaner documents than DBRef, but resolving a list of references still runs per entity unless the lookup is written to batch, so check your version's behaviour before relying on it for list pages.

4Fix 2: Embed What Is Always Shown Together

Some references exist only because the model was copied from relational tables. If every order view shows the customer's name and every order line shows the product name and price, the natural document design is to store those fields in the order itself. An order line should keep the price at the time of purchase anyway, so copying it is not just faster but more correct.

YAML
{
_id: ObjectId("..."), status: "OPEN",
customer: { id: "c-17", name: "Ana Lima" }, // a small copy, not a reference
lines: [ { productId: "p-3", name: "Desk lamp", price: 39.90, qty: 1 } ]
}

The cost of copying is keeping the copy fresh when the source changes. For fields that rarely change, such as a customer's name, a background update or an event handler that updates the copies is usually acceptable. For fields that change constantly, such as stock levels, we keep a reference and load in batches.

5Fix 3: Use $lookup for Read Models

For screens that need joined data, such as an admin report of orders with customer details, an aggregation with $lookup does the join on the server in one round trip.

Java
Aggregation agg = Aggregation.newAggregation(
Aggregation.match(Criteria.where("status").is("OPEN")),
Aggregation.lookup("customers", "customerId", "_id", "customer"),
Aggregation.unwind("customer"),
Aggregation.project("status", "customer.name", "customer.email"));
List<OrderRow> rows = mongoTemplate.aggregate(agg, "orders", OrderRow.class).getMappedResults();
// 1 round trip

Notice the type conversion detail: $lookup compares values exactly, so if customerId is stored as a string and _id as an ObjectId, nothing matches. That is a common surprise when migrating from DBRef, and a good reason to agree on id types during the migration.

6Migrating Across a Large Codebase

Changing every entity at once in a large codebase is risky. We go endpoint by endpoint, starting with the slowest and most used. First we write a test that counts the queries an endpoint sends, using a command listener registered on the MongoDB client in an integration test with Testcontainers, and assert today's number. Then we change the model or the service, and tighten the assertion to the new number so it can never quietly grow back.

For the data itself, we can add the plain id field next to the DBRef, write both for a while, backfill old documents in batches, switch the reads, and finally remove the DBRef field. Each step is deployable on its own. We also add a code review rule that new @DBRef fields need a reason, so the pattern stops spreading while we remove it.

Step throughReplacing @DBRef one endpoint at a time
  1. Pick the slowest list endpointfrom metrics or traces
  2. Write a query-count testassert today's number, for example 201
  3. Always shown with the parent?
    YesEmbed a small copyNoStore the id
  4. Load related ids with one $in queryor $lookup for a read model
  5. Backfill old documents in batchesthen remove the DBRef field
  6. Tighten the test to the new countfor example 3

6 steps in order. Play them, or step through them one at a time.

7Follow-up questions

Is @DBRef ever the right choice?

Rarely in new code. It can be acceptable when a single document is loaded and the reference is used occasionally, such as an admin screen that opens one item. For lists and APIs, explicit ids with batch loading or embedded copies are almost always faster and easier to reason about.

Does lazy = true fix the N+1 problem?

No. It only delays each query until the proxy is used. If the code or the JSON serializer touches every reference, we still run one query per reference, just later and less visibly. It helps only when most references are never accessed.

How do we count queries in a test?

Register a CommandListener on the MongoClientSettings used by the test, count the find, aggregate and getMore commands it sees while the endpoint runs, and assert the number. With Spring Boot this can be done through a MongoClientSettingsBuilderCustomizer bean in the test configuration.

8Conclusion

In this answer, we saw that @DBRef resolves each reference with its own query, eagerly or through lazy proxies, which turns list pages into N+1 query patterns. We replaced it with plain ids loaded in batches with $in, with @DocumentReference where it fits our version, with embedded copies of fields always shown together, and with $lookup aggregations for read models. Across a large codebase we migrate one endpoint at a time, protected by tests that count the queries each endpoint sends.

What to say in the interviewAbout 90 seconds aloud

Open with

The problem is that @DBRef resolves every reference with its own findById, either eagerly or later through a lazy proxy, so a page of 50 orders with a customer and three products each becomes about 200 round trips.

Then, if they want more

I would start by measuring with the driver's command logging or the profiler to know the real numbers per endpoint. Then I would fix it in layers.

Where the referenced data is always shown with the parent and rarely changes, like a customer name on an order or the price on an order line, I embed a small copy, which is the natural document design.

Where it changes often, I store the id as a plain field and load all related documents for a page in one $in query with findAllById, so it is one extra query instead of N. @DocumentReference can replace DBRef with cleaner stored values, but I would check how my version resolves lists.

For reporting and admin read models, an aggregation with $lookup does the join on the server in one trip, as long as the id types match. Across a big codebase I migrate endpoint by endpoint, slowest first, with an integration test that counts queries using a command listener, write both fields during the transition, backfill, then remove the DBRefs.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
MongoDB manual
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A large Spring Data MongoDB codebase uses @DBRef everywhere, and loading lists is slow...": https://scrivio-interview-library.netlify.app/databases/mongodb/8e0dcda42f/