skip to content

MongoRepository

MongoRepository supports derived queries, raw JSON filters via @Query, whole pipelines via @Aggregation, and geospatial keywords. The familiar repository model over a document store, and interviewers check you know where it stops being enough.

part ofSpring Frameworkoverview, primer and where to startread it →
on this pageshow

questions

5

What is a MongoRepository and how do derived (query-method) queries work in Spring Data MongoDB?

level: juniorimportance: must knowfreq 75%

answer

  1. interface only -> proxy at startup
  2. subject (find/count/exists/delete) + predicate
  3. And/Or/Between/In/Like/IgnoreCase/OrderBy
  4. Pageable=Page(+count) vs Slice(no count)
  5. bad property name = boot failure

basics

~20 s

MongoRepository is a Spring Data interface for a MongoDB collection giving CRUD out of the box. You add method names like findByLastName, and Spring parses the name into a query automatically — no implementation code needed.

solid answer

~40 s

MongoRepository<T, ID> extends CrudRepository/PagingAndSortingRepository and gives you save, findById, findAll, delete, etc. for a document type mapped to a collection. You declare an interface; Spring Data generates a proxy at startup. Derived queries come from the method name: Spring parses a subject (find/count/exists/delete) plus a predicate (findByLastNameAndAge) into a MongoDB query using the entity's mapped fields. Keywords like And, Or, Between, LessThan, In, Like, IgnoreCase, OrderBy build the criteria. You can return T, Optional<T>, List<T>, Page<T>, or Stream<T>, and add Pageable/Sort parameters. Field names in the method must match the mapped property names; a typo fails fast at bootstrap. For complex logic you switch to @Query or @Aggregation instead of ever-longer method names.

code

java · 20 lines
java
@Document(collection = "users")
public class User {
    @Id private String id;
    private String lastName;
    private int age;
    // getters/setters
}

public interface UserRepository extends MongoRepository<User, String> {

    List<User> findByLastNameIgnoreCase(String lastName);

    List<User> findByAgeBetweenOrderByAgeDesc(int min, int max);

    Page<User> findByLastName(String lastName, Pageable pageable);

    long countByAgeGreaterThan(int age);

    Optional<User> findFirstByLastName(String lastName);
}

go deeper

for a junior

Know MongoRepository gives CRUD and that findByX methods are auto-implemented from the name.

for a middle

Know the keyword vocabulary, return types, and Pageable/Sort mechanics.

for a senior

Explain Page-vs-Slice count cost, property-path resolution, fail-fast at boot, and when to graduate to @Query.

for a principal

Reason about index usage of regex-based keywords, lifecycle-event cost of delete-by, and repository-fragment composition for custom behavior.

**MongoRepository** is the MongoDB-specific repository interface in Spring Data MongoDB. You define an interface such as `interface UserRepository extends MongoRepository<User, String>` where `User` is your document class (annotated `@Document(collection = "users")`) and `String` is the `@Id` type. At application startup, Spring Data's repository infrastructure creates a **dynamic proxy** implementing your interface — you never write the implementation. It layers on top of `MongoTemplate`, the lower-level API. **What you get for free:** `MongoRepository` extends `CrudRepository` and `PagingAndSortingRepository` (via `ListCrudRepository`/`ListPagingAndSortingRepository` in newer versions), so you inherit `save`, `saveAll`, `findById`, `existsById`, `findAll`, `findAllById`, `count`, `deleteById`, `delete`, `deleteAll`, plus `findAll(Sort)` and `findAll(Pageable)`. **Derived / query-method queries:** Instead of writing a query, you name a method and Spring Data parses the name into a query. The name splits into a **subject** and a **predicate**: - Subjects: `findBy`, `readBy`, `getBy`, `queryBy`, `searchBy`, `streamBy` (all read), `countBy`, `existsBy`, `deleteBy`/`removeBy`. - Predicate: property expressions joined by `And`/`Or`, e.g. `findByLastNameAndFirstName`. **Supported keywords** map to MongoDB operators: `Is`/`Equals`, `Not` (`$ne`), `Between` (`$gt`+`$lt`), `LessThan`/`LessThanEqual` (`$lt`/`$lte`), `GreaterThan`/`GreaterThanEqual`, `Before`/`After`, `IsNull`/`IsNotNull`, `Like`/`NotLike`/`StartingWith`/`EndingWith`/`Containing` (regex-based), `Regex`, `In`/`NotIn` (`$in`/`$nin`), `True`/`False`, `Near`/`Within` (geo), `Exists`, `IgnoreCase`, and `OrderBy...Asc/Desc` for sorting. **Return types:** `T`, `Optional<T>`, `List<T>`, `Stream<T>`, `Page<T>`, `Slice<T>`, `GeoResults<T>`, or reactive `Mono`/`Flux`. Adding a `Pageable` parameter enables paging (`Page` runs an extra count query; `Slice` does not); a `Sort` parameter or `OrderBy` clause sorts. **Property matching:** The parser resolves each path against the mapped document properties (respecting `@Field` names). Ambiguous camel-case paths can be disambiguated with underscores, e.g. `findByAddress_ZipCode`. A property name that doesn't resolve causes a **startup failure** — fail-fast, not runtime. **Gotchas:** method names get unwieldy fast — beyond ~3 conditions prefer `@Query`. `Like`/`Containing` translate to regex and can be slow / bypass indexes if not anchored. `delete...By` returns the deleted documents or a count and loads them first (fires lifecycle events) unlike bulk deletes. Field names are the *mapped* names, not necessarily the Java field if `@Field` renames them. **When to use:** derived queries for simple, readable finders; `@Query` for JSON filters MongoDB-native; `@Aggregation` for pipelines; `MongoTemplate` for fully dynamic/programmatic queries.

  • What happens if you name a derived method with a property the document doesn't have?
    Spring Data fails fast at application startup while creating the repository proxy — it cannot resolve the property path, so you get a bootstrap exception rather than a runtime error later.
  • Difference between returning Page<T> and Slice<T> with a Pageable?
    Page issues an extra count query so it knows total elements/pages; Slice only fetches pageSize+1 to know if a next page exists, avoiding the count — cheaper when you only need next/prev navigation.

saying these in an interview costs you the question

  • Thinking you must write the query body — the proxy generates it from the name
  • Believing a misspelled property fails only at runtime (it fails at startup)
  • Assuming Like uses a full-text index (it compiles to a regex)

context

open as a page

How does the @Query annotation work on a MongoRepository method, and when would you use it over a derived method?

level: middleimportance: must knowfreq 70%

basics

~20 s

@Query lets you write the raw MongoDB query as a JSON filter string on a repository method, with ?0, ?1 placeholders for arguments. Use it when the query is too complex for a readable derived method name.

open as a page

Explain the @Aggregation annotation on a MongoRepository — how pipeline methods work and their key features.

level: seniorimportance: should knowfreq 55%

basics

~20 s

@Aggregation lets a repository method run a MongoDB aggregation pipeline. You supply an array of pipeline stage strings ($match, $group, $sort, ...) with ?0 placeholders, and Spring maps each output document to the method's return type.

open as a page

How do geospatial Near queries work in a Spring Data MongoDB repository — the Near/Within keywords, index requirement, and GeoResults?

level: seniorimportance: should knowfreq 40%

basics

~20 s

You add a derived method with the Near keyword taking a Point and a Distance, e.g. findByLocationNear(Point p, Distance d). The location field needs a geospatial index (@GeoSpatialIndexed), and returning GeoResults gives each hit's distance.

open as a page

Across derived queries, @Query, @Aggregation, and MongoTemplate — how do you choose the right query mechanism, and what are the tradeoffs?

level: principalimportance: should knowfreq 45%

basics

~10 s

Use derived methods for simple readable finders, @Query for native JSON filters/projections too complex for a name, @Aggregation for grouping and multi-stage pipelines, and MongoTemplate when the query must be built dynamically at runtime.

open as a page