这是我的JSON。
{
"_id" : ObjectId("5c7a590350d039fdc86e4e37"),
"cropData" : {
"cropName" : "RICE",
"crop" : "RICE",
"cropAcres" : 10.0,
"cropYield" : 73.0,
"cropPrice" : 3619.0
},
"creationTime" : "1551521509975",
"villageId" : "581edb59e4b0b5b1ebbfe757"
}
“收藏夹”中有1000个这样的条目,名为FarmerCropDataLog
。我想从这个FarmerCropDataLog
中获取特定村庄的最高和平均值。为此,我编写了以下代码。
public void getSheet(GetComparisonSheetRequest getComparisonSheet, BasicResponse response,String requestFarmerId) {
Farmer farmer = this.getFarmerById(requestFarmerId);
// get logs before this year..
String villageId = farmer.getVillageId();
MatchOperation matchOperation = Aggregation.match(Criteria.where(FarmerCropDataLog.Constants.CROP_LOG).elemMatch(Criteria.where(CropData.Constants.CROP).is(getComparisonSheet.getCrop()))
.andOperator(Criteria.where(FarmerCropDataLog.Constants.VILLAGE_ID).is(villageId))
.andOperator(Criteria.where(FarmerCropDataLog.Constants.CREATION_TIME).gt(LAST_YEAR)));
GroupOperation groupOperation = Aggregation.group(FarmerCropDataLog.Constants.VILLAGE_ID);
groupOperation.avg(CropData.Constants.CROP_PRICE).as("averageIncome");
groupOperation.max(CropData.Constants.CROP_PRICE).as("maxIncome");
Aggregation aggregation = Aggregation.newAggregation(matchOperation,groupOperation);
AggregationResults<GetComparisonSheetResponse> aggregationResults = farmerCropDataLogDAO.runAggregation(aggregation,FarmerCropDataLog.class,GetComparisonSheetResponse.class);
List<GetComparisonSheetResponse> getResult = aggregationResults.getMappedResults();
GetComparisonSheetResponse comparisonSheetResponse = getResult.get(0);
response.setResponse(comparisonSheetResponse);
response.setSuccess(true);
}
尝试运行farmerCropDataLogDAO.runAggregation
时出现错误。它引发异常,我该如何成功运行?
引发异常:
Due to limitations of the com.mongodb.BasicDBObject, you can't add a second '$and' expression specified as '$and : [ { "creationTime" : { "$gt" : 1471228928}}]'. Criteria already contains '$and : [ { "villageId" : "5b0ed0bc77c8ae9704f65c43"}]'.
答案 0 :(得分:1)
好的,所以感谢他,我通过更改@Neil建议的代码来解决了我的问题。
我已从
更改了此代码MatchOperation matchOperation = Aggregation.match(Criteria.where(FarmerCropDataLog.Constants.CROP_LOG).elemMatch(Criteria.where(CropData.Constants.CROP).is(getComparisonSheet.getCrop()))
.andOperator(Criteria.where(FarmerCropDataLog.Constants.VILLAGE_ID).is(villageId))
.andOperator(Criteria.where(FarmerCropDataLog.Constants.CREATION_TIME).gt(LAST_YEAR)));
对此->
MatchOperation matchOperation = Aggregation.match(Criteria.where(FarmerCropDataLog.Constants.CROP_LOG).elemMatch(Criteria.where(CropData.Constants.CROP).is(getComparisonSheet.getCrop())
.and(FarmerCropDataLog.Constants.VILLAGE_ID).is(villageId)
.and(FarmerCropDataLog.Constants.CREATION_TIME).gt(LAST_YEAR)));