【发布时间】:2019-05-24 16:03:10
【问题描述】:
我想将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);
由此产生的结果是空的。我不明白为什么?
【问题讨论】:
-
你能发布原始的 mongo 聚合吗?
-
@Bajal 你能详细说明一下吗?我不明白,
-
你能发布等效的 mongo 聚合查询吗?然后可以映射回你在spring-data-mongo中写的Java API代码
-
好的,你能写一个例子,划分 2 个字段并给出 list
作为结果 -
将查询添加为答案。希望你能写出同样的java代码。
标签: spring mongodb mongodb-query