user13709439
user13709439

Reputation:

Convert mongoDB query into Spring Data MongoDB java code

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

Upvotes: 1

Views: 280

Answers (1)

Valijon
Valijon

Reputation: 13093

Try this way:

Aggregation.group("operationId").first("$$ROOT").as("g");
Aggregation.replaceRoot("g");

Upvotes: 1

Related Questions