我正在使用“聚合”从村庄的cropPrice获取平均值和最大值。为此,我编写了以下代码。
public void getComparisonSheet(GetComparisonSheetRequest getComparisonSheet, BasicResponse response,
String requestFarmerId) {
Farmer farmer = this.getFarmerById(requestFarmerId);
// get logs before this year...
String villageId = farmer.getVillageId();
Criteria criteria = Criteria.where(FarmerCropDataLog.Constants.CROP_LOG).is(getComparisonSheet.getCrop().name())
.and(FarmerCropDataLog.Constants.VILLAGE_ID).is(villageId)
.and(FarmerCropDataLog.Constants.CREATION_TIME).gt(LAST_YEAR);
MatchOperation matchOperation = Aggregation.match(criteria);
Fields fields = Fields.fields(CropData.Constants.CROP_PRICE,FarmerCropDataLog.Constants.VILLAGE_ID);
ProjectionOperation projectionOperation = Aggregation.project(fields);
Fields groupFields = Fields.fields(FarmerCropDataLog.Constants.VILLAGE_ID);
GroupOperation groupOperation = Aggregation.group(groupFields);
groupOperation.avg(CropData.Constants.CROP_PRICE).as(GetComparisonSheetResponse.Constants.AVERAGE);
groupOperation.max(CropData.Constants.CROP_PRICE).as(GetComparisonSheetResponse.Constants.MAX_INCOME);
LimitOperation limitOperation = new LimitOperation(MAX_RESULTS);
AggregationOptions aggregationOptions = Aggregation.newAggregationOptions().allowDiskUse(true).explain(false).cursor(new BasicDBObject()).build();
Aggregation aggregation = Aggregation.newAggregation(matchOperation, projectionOperation, groupOperation
,limitOperation).withOptions(aggregationOptions);
AggregationResults<GetComparisonSheetResponse> aggregationResults = farmerCropDataLogDAO
.runAggregation(aggregation, FarmerCropDataLog.class, GetComparisonSheetResponse.class);
List<GetComparisonSheetResponse> comparisonSheetResponses = aggregationResults.getMappedResults();
response.setResponse(comparisonSheetResponses);
response.setSuccess(true);
}
这是我的FarmerCropDataLog实体结构。
public class FarmerCropDataLog extends AbstractEntity {
private String farmerId;
private CropData cropData;
private String villageId;
}
从代码中可以看到,它首先按villageId,Creation Time和crop查找所有实体,然后根据villageId和cropPrice进行投影,最后将其组合在villageId上,以便找出特定对象的平均收入和最高收入村庄,但返回结果为空。