pnewhook
pnewhook

Reputation: 4078

Combine Document and AggregationOperation Stages in a Spring MongoDB Aggregation Pipeline?

Spring Data MongoDB has helpful builder classes for aggregation stages, like Aggregation.match() or Aggregation.sort(). Objects returned by those methods implement the AggregationOperation interface, which allows them to be used Aggregation.newAggregation() to create a new pipeline, which is in turn passed to mongoTemplate.aggregate().

The problem is not all Mongo aggregation stages have builder methods, e.g. $lookup with a correlated subquery. It appears in those cases I have to manually create a Document with JSON describing the stage. But I can't find a way to use an AggregationOperation and a Document based stage together. Is there a way to wrap a Document into an AggregationOperation, or similar?

Upvotes: 1

Views: 1257

Answers (1)

Valijon
Valijon

Reputation: 13103

This is an issue / feature that remains open to this day spring-data-mongodb - #3322

Workaround: Implement AggregationOperation interface

Java 1.7

AggregationOperation lookup = new AggregationOperation() {

    @Override
    public Document toDocument(AggregationOperationContext context) {
        return new Document(...); // put here $lookup stage
    }

};

>= Java 1.8

AggregationOperation lookup = ctx -> new Document(...); // put here $lookup stage

Upvotes: 2

Related Questions