MongoDB integration

Dynamic MongoDB search and aggregation for Spring Boot microservices

Spring Middleware provides a dynamic query layer on top of Spring Data MongoDB. It translates typed search DTOs into MongoDB queries and aggregation pipelines, making search behavior reusable, explicit, and consistent across Spring Boot microservices.

Dynamic search DTOs Aggregation pipelines Generated query JSON Pagination support Geo queries Reusable query builders

What the Mongo module provides

The Mongo module adds dynamic search and aggregation helpers on top of Spring Data MongoDB. Instead of hardcoding query logic in each repository, services can define typed search DTOs and let the platform translate them into queries and aggregation stages.

  • Dynamic find, count, and aggregate operations
  • Typed search DTO to query translation
  • Pagination and result helpers
  • Support for geo queries and nested criteria

Core runtime pieces

  • MongoSearchRepositoryImpl: repository base for dynamic find, count, and aggregate operations.
  • CriteriaBuilderComponent: builds MongoDB Criteria objects.
  • QueryCreatorComponent: creates Query instances from search DTOs.
  • PipeLineBuilderComponent: builds aggregation pipelines.
  • AddFieldsBuilderComponent: builds computed fields inside aggregation stages.

How it works

The module uses a small processing pipeline that inspects a MongoSearch DTO and translates annotated fields into MongoDB criteria and aggregation stages.

01

Define a search DTO

Create a typed MongoSearch DTO describing the search fields for your domain.

02

Process properties

Property processors inspect DTO fields and decide how they map to equality, range, OR, geo, or nested criteria.

03

Build query or pipeline

The builder components translate the DTO into a MongoDB Query or Aggregation.

Property-level processing

MongoSearchPropertyProcessor applies annotation semantics and field mapping rules to produce query fragments for equality, ranges, OR/AND combinations, geo conditions, and nested arrays.

Class-level orchestration

MongoSearchClassProcessor and related processors orchestrate the translation of the full DTO, composing nested criteria and delegating to query and aggregation builders.

Repository usage

Services define a search DTO, extend the repository contract, and use high-level methods such as findBySearch, aggregateBySearch, and countBySearch.

Repository example

public interface ProductSearchRepository
    extends MongoSearchRepository<Product, ProductSearch> {
}

Service usage example

@Autowired
private ProductSearchRepository productSearchRepository;

Pagination pagination = new Pagination(0, 20);

Page<Product> page =
    productSearchRepository.findBySearch(searchDto, pagination);

Generated query examples

The module test suite shows how typed search DTOs are translated into MongoDB criteria and aggregation JSON. These examples illustrate the kind of queries the builders generate.

Simple equality

{
  "$and": [ { "key": "KEY" } ]
}

Combined conditions

{
  "$and": [ { "value": "VALUE" }, { "key": "KEY" } ]
}

Nested sub-search

{
  "$and": [
    { "$and": [ { "subSearch.propA": "PROP_A" }, { "subSearch.propB": "PROP_B" } ] },
    { "key": "KEY" }
  ]
}

OR conditions

{
  "$or": [ { "orB": "OR_B" }, { "orA": "OR_A" } ]
}

Nested arrays and aggregation stages

The module also supports nested array matching and computed fields through aggregation pipeline builders.

Nested arrays with elemMatch

{
  "$and": [
    {
      "itemSearch": {
        "$elemMatch": {
          "$and": [
            { "propItemA": "PROP_ITEM_A" },
            { "propItemB": "PROP_ITEM_B" }
          ]
        }
      }
    }
  ]
}

AddFields example

{
  "$addFields": {
    "itemSearch": {
      "$map": {
        "input": "$itemSearch",
        "as": "u",
        "in": {
          "propAB": { "$concat": ["$$u.propA", " ", "$$u.propB"] },
          "propItemA": "$$u.propItemA",
          "class": "$$u.class",
          "propItemD": "$$u.propItemD",
          "propItemC": "$$u.propItemC",
          "propItemB": "$$u.propItemB"
        }
      }
    }
  }
}

Pagination, aggregation, and geo queries

The repository helpers support pagination and can build richer aggregations and geo-aware criteria from the search DTO and processing components.

Pagination

Use the provided Pagination DTO and result wrappers when executing findBySearch(...).

Aggregation pipelines

Pipelines can combine stages such as $addFields, $match, $group, $project, $sort, $skip, and $limit.

Geo queries

Geo-related fields in the search DTO can generate criteria such as nearSphere and geoWithin where appropriate.

Extending the module

The module is intentionally extensible. Builder components and processors can be customized to support project-specific operators or mappings.

Customize builders

Extend or override components such as CriteriaBuilderComponent or AddFieldsBuilderComponent to add custom query operators.

Reuse repository entry points

Keep using MongoSearchRepositoryImpl and its high-level methods while adapting the translation logic to project-specific search needs.

Best practices

Dynamic query infrastructure is powerful, but it should remain bounded and explicit.

Keep search DTOs focused

Avoid large unconstrained DTOs that can generate overly broad or expensive queries.

Validate search inputs

Apply validation to page size, geo radius, and user-controlled search parameters.

Use computed fields carefully

$addFields is powerful, but can make aggregations more expensive if overused.

Where to look in the code

The Mongo module is centered around repository helpers, processors, and builder components.

MongoSearchRepositoryImpl

mongo core

.../mongo/repository/MongoSearchRepositoryImpl.java

CriteriaBuilderComponent

mongo components

.../mongo/components/CriteriaBuilderComponent.java

PipeLineBuilderComponent

mongo components

.../mongo/components/PipeLineBuilderComponent.java

Mongo processors

mongo core-commons

.../mongo/processor/*