1

I have the following MongoDB query and I dont know how to convert in Spring Data java code, the group and replaceRoot operations.

db.getCollection('operationData').aggregate([

    { $match: type: "OPERATION_CHEAP", amount: {$gte: 1000}, 
              createdAt: {$gte: ISODate("2020-01-24T23:00:00.000Z")}
    },

    { $project: { amount: 1, operationId: 1 } },

    { $sort: { amount: -1 } },

    { $group: { _id: '$operationId', g: { $first: {data: '$$ROOT'} }} }, <----
        
    { $replaceRoot: { newRoot: '$g.data' }}, <------
            
    { $sort: { amount: 1 } }

])

This is the code for the match operation:

 Criteria criterias = new Criteria()
            .andOperator(Criteria.where(Operation.AMOUNT)
            .gte(minAmount)
            .and(Operation.TYPE).is(OperationTypeEnum.CHEAP_OPERATION)
            .and("createdAt").gte(startDate).lte(endDate));

 MatchOperation matchOperation = Aggregation.match(criterias);

This is the code for the project operation:

ProjectionOperation projectionOperation = Aggregation.project("amount", "operationId");

And this is the Aggregation operation:

Aggregation aggregation = Aggregation.newAggregation(matchOperation, projectionOperation,
                                                     sort(direction, "amount"));
AggregationResults<OperationDataVO> aggregate = mongoTemplate.aggregate(aggregation, 
                                                     COLLECTION, OperationDataVO.class);

I cant find out how to create and integrate the GroupOperation

1
  • 1
    A useful workaround when you have an aggregation that works in the mongo shell, but you don't know how to convert it to a Spring aggregation : stackoverflow.com/a/59726492/5873923 Commented Jun 26, 2020 at 8:28

1 Answer 1

1

Try this way:

Aggregation.group("operationId").first("$$ROOT").as("g");
Aggregation.replaceRoot("g");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.