我想将cropYield除以cropAcres,我的数据格式如下,并且我有1000个。因此,我需要为每个条目获取此cropYield/cropAcres
的数组作为数组。这是我的 FarmerCropDataLog 集合。
{
"_id": "5ce681e14e8e8aec5a7e9ac4",
"_class": "com.cheruvu.webapp.entity.FarmerCropDataLog",
"farmerId": "5cdc16214e8e21271cb3af5e",
"cropData": {
"cropName": "COTTON",
"crop": "COTTON",
"cropAcres": 2,
"cropYield": 10,
"cropPrice": 9000
},
"villageId": "5b0ed0bd77c8ae9704f65c97",
"creationTime": "1558610401404",
"lastUpdated": "1558610996163",
"state": "ACTIVE"
}
这是我尝试过的。
// I need to fetch all users(farmers) with same VillageId, same crop and which are added in last year.
Criteria criteria = Criteria.where(FarmerCropDataLog.Constants.CROP).is(getComparisonSheet.getCrop().name())
.and(FarmerCropDataLog.Constants.VILLAGE_ID).is(villageId)
.and(FarmerCropDataLog.Constants.CREATION_TIME).gte(LAST_YEAR);
MatchOperation matchOperation = Aggregation.match(criteria);
// then via projection i am getting cropYield and divide it via cropAcres.
ProjectionOperation projectionOperation = Aggregation.project(FarmerCropDataLog.Constants.CROP_YIELD);
ProjectionOperationBuilder builder = new ProjectionOperationBuilder("op1", projectionOperation, null);
builder = builder.divide(FarmerCropDataLog.Constants.CROP_ACRES);
projectionOperation = builder.as(GetYieldComparisonResponse.Constants.MAX_YIELD);
// and at last i am running this operation via following code.
AggregationOptions aggregationOptions = Aggregation.newAggregationOptions().allowDiskUse(true).explain(false)
.cursor(new BasicDBObject("batchSize", 100)).build();
Aggregation aggregation = Aggregation.newAggregation(matchOperation,projectionOperation)
.withOptions(aggregationOptions);
AggregationResults<GetYieldComparisonResponse> aggregationResults = farmerCropDataLogDAO
.runAggregation(aggregation, FarmerCropDataLog.class, GetYieldComparisonResponse.class);
由此产生的结果为空。我不明白为什么?
答案 0 :(得分:0)
您可以像这样使用$divide
聚合函数。根据需要添加更多字段以进行投影,这里我投影了farmerId和相应的产量/英亩值。
db.FarmerCropDataLog.aggregate([
{ $project: { farmerId: 1,
yieldPerAcre: { $divide: [ "$cropData.cropYield", "$cropData.cropAcres" ] } } }
])