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
    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 : https://stackoverflow.com/a/59726492/5873923 – Marc Tarin Jun 26 '20 at 08:28

1 Answers1

1

Try this way:

Aggregation.group("operationId").first("$$ROOT").as("g");
Aggregation.replaceRoot("g");
Valijon
  • 12,667
  • 4
  • 34
  • 67