Quick revision
The short answer
We annotate Order with @Document(collection = "orders"), give it an @Id, a customerId, a createdAt Instant and a List<Line>, where Line is a plain class with no annotations because it is stored inside the order document. The repository extends MongoRepository<Order, String> and declares findByCustomerIdOrderByCreatedAtDesc(String customerId), which Spring Data turns into a query with a sort. We add a compound index on customerId and createdAt ourselves, because automatic index creation is off by default.
What to remember
In this answer, we mapped Order with @Document and @Id and embedded Line as a plain record, so an order and its lines live in one document. The derived method findByCustomerIdOrderByCreatedAtDesc becomes a filter plus a descending sort, and adding a Pageable keeps it bounded. A compound index on customerId and createdAt makes the query fast, but it must be created explicitly or enabled, because automatic index creation is off by default. MongoTemplate covers the cases where we need precise queries and in-place updates.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We annotate Order with @Document(collection = "orders"), give it an @Id, a customerId, a createdAt Instant and a List<Line>, where Line is a plain class with no annotations because it is stored inside the order document. The repository extends MongoRepository<Order, String> and declares findByCustomerIdOrderByCreatedAtDesc(String customerId), which Spring Data turns into a query with a sort. We add a compound index on customerId and createdAt ourselves, because automatic index creation is off by default.
Why this question is asked
This is a small coding question, but it shows whether we understand the main idea of a document database: data that is read together is stored together. An order and its lines are a classic example. Interviewers also listen for whether we know how derived query methods work and whether we remember the index, which is the part that decides if the query takes 2 milliseconds or 2 seconds once the collection grows. In this answer, we will recap how Spring Data MongoDB maps classes, write the Order and Line classes, write and explain the repository method, add the index, and see when MongoTemplate is the better tool.
1A Quick Recap of Documents and Mapping
MongoDB stores documents, which are JSON-like objects saved in a binary format called BSON, and groups them into collections, roughly the equivalent of tables. A document can contain nested objects and arrays, so one document can hold an order together with all its lines. Spring Data MongoDB maps a Java class to such a document: each field becomes a key, nested objects become nested documents, and lists become arrays.
Only the top-level class needs @Document, which tells Spring Data which collection to use. Classes that are only ever stored inside another document are called embedded, and they need no annotation at all. Because the lines are inside the order, reading an order brings its lines with it in one read, and no join is needed.
2Writing the Order and Line Classes
Here is the mapping. We keep the classes small and use a record for the line, which Spring Data MongoDB supports through its constructor-based mapping.
Notice three things. The @Id field becomes MongoDB's _id, and when it is a String Spring Data converts it to an ObjectId, a 12-byte identifier MongoDB generates. The lines are an array inside the same document, so they are written and read atomically with the order. And Spring Data adds a _class key holding the type name, which it uses when reading the document back; it can be turned off if we never store subclasses in the same collection. BigDecimal is stored as Decimal128 in recent Spring Data versions when configured that way; check your version's default, because older ones stored it as a string.
3The Repository Method and What It Turns Into
A repository is an interface Spring Data implements for us at runtime. Extending MongoRepository<Order, String>, where String is the type of the id, gives us save, findById, delete and friends. Then we add one method whose name describes the query.
- findBystart a find query
- CustomerIdfilter {
customerId: ?0 } - OrderByCreatedAtDescsort {
createdAt: -1 } - Pageable argumentskip and limit
- Index on customerId, createdAtlets MongoDB read in order, no in-memory sort
5 steps in order. Play them, or step through them one at a time.
Spring Data parses the method name when the application starts. findBy starts a query, CustomerId becomes a filter on the customerId field, and OrderByCreatedAtDesc adds a descending sort. If we misspell a field, the application fails to start, which is a useful early check. The second version with a Pageable is what we would use in real code: a long-time customer may have thousands of orders, and loading all of them into a list for a screen that shows twenty is wasteful.
4Adding the Index
Without an index, MongoDB must scan every order in the collection to find one customer's orders and then sort them in memory. A compound index on customerId ascending and createdAt descending lets it jump to that customer's entries and read them already in the right order.
There is a catch. The @CompoundIndex annotation above only describes the index; since Spring Data MongoDB 3.0, automatic index creation is disabled by default, so nothing creates it unless we set spring.data.mongodb.auto-index-creation=true (check the property name for your Spring Boot version, since Boot 4 reorganised some MongoDB properties). Many teams prefer to create indexes explicitly in migration scripts, for example with Mongock or a plain script run by the pipeline, because building an index on a large collection takes time and should not happen as a side effect of a deployment.
5When to Reach for MongoTemplate
Derived methods cover simple finds. MongoTemplate gives full control over queries and updates when we need more, for example updating one field inside a document without reading and rewriting the whole order.
The $push update appends to the array on the server in one atomic operation, so two concurrent requests adding lines do not overwrite each other, which a read-modify-save through the repository could do.
6Follow-up questions
Why not store lines in their own collection?
Because lines have no life of their own: they are created with the order, read with the order, and deleted with it. Embedding them gives one read, one atomic write and no join. A separate collection would only make sense if lines were queried on their own at scale or could grow without limit.
What happens if the list of lines gets very large?
A MongoDB document is limited to 16 MB, and large arrays make every read and update heavier. An order rarely has more than a few hundred lines, so it is fine here, but an unbounded array such as all events for a customer should not be embedded.
Should the repository return List or Stream or Page?
Page also runs a count query, which costs extra on large collections; Slice or a List with a Pageable avoids that when the screen only needs a next-page link. For processing many orders in a batch, a Stream return type reads with a cursor instead of loading all into memory, and it must be closed after use.
7Conclusion
In this answer, we mapped Order with @Document and @Id and embedded Line as a plain record, so an order and its lines live in one document. The derived method findByCustomerIdOrderByCreatedAtDesc becomes a filter plus a descending sort, and adding a Pageable keeps it bounded. A compound index on customerId and createdAt makes the query fast, but it must be created explicitly or enabled, because automatic index creation is off by default. MongoTemplate covers the cases where we need precise queries and in-place updates.
Open with
I would put @Document with collection orders on the Order class, with an @Id String id, a customerId, a createdAt Instant and a List of Line. Line is just a plain class or a record with no annotations, because it is embedded inside the order document, so reading an order gives me the lines in one read with no join, and saving it is atomic.
Then, if they want more
The repository extends MongoRepository of Order and String and declares findByCustomerIdOrderByCreatedAtDesc taking the customer id. Spring Data parses that name at startup into a find on customerId with a sort on createdAt descending, and in practice I would add a Pageable so a customer with thousands of orders does not load all of them.
The part people forget is the index. I would add a compound index on customerId ascending and createdAt descending, so MongoDB can find the customer's orders and read them already sorted.
I can declare it with @CompoundIndex, but automatic index creation is off by default since Spring Data MongoDB 3, so I either enable it or, more often, create the index in a migration script and check explain shows an index scan.
For anything beyond simple finds, like pushing a new line into the array atomically, I would use MongoTemplate with a Query and an Update.
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
- Spring Data reference
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 "Map an Order document with embedded line items in Spring Data MongoDB, and write a...": https://scrivio-interview-library.netlify.app/databases/spring-data-nosql/613b8c645f/