改进聚合查询以获得不同的结果

时间:2020-06-23 14:25:55

标签: java mongodb aggregation-framework projection mongotemplate

我有一个聚合查询,返回的Operation对象的字段amount:BigDecimal高于minAmount并且在日期范围内。我只想得到不同的结果(每个{{1} }对象基于Operation有一个operationId:String

我在这里找到了一个相关的例子,但是并没有帮助我解决我的问题:Get sorted distinct values with MongoTemplate

我知道可以使用operationIdaddToSet,但尚不清楚在其余查询中如何准确地整合它

group

我还尝试在 private List<OperationDataVO> getInfoFromDB(BigDecimal minAmount, Instant startDate, Instant endDate) { Criteria criterias = new Criteria() .andOperator(Criteria.where(WinningOperation.AMOUNT) .gte(minAmount) .and(Operation.TYPE).is(OperationTypeEnum.WINNING_TYPE) .and("createdAt").gte(startDate).lte(endDate)); MatchOperation matchOperation = Aggregation.match(criterias); ProjectionOperation projectionOperation = Aggregation.project("amount", "operationId"); Aggregation aggregation = Aggregation.newAggregation(matchOperation, projectionOperation, sort(direction, "amount")); AggregationResults<OperationDataVO> aggregate = mongoTemplate .aggregate(aggregation, COLLECTION, OperationDataVO.class); return aggregate.getMappedResults(); } 管道中添加组操作,但是这样做时,我得到了Aggregation的列表,其中每个对象的两个字段均为OperationDataVO < / p>

null

1 个答案:

答案 0 :(得分:0)

在进行分组之前,您需要按amount降序排列。 分组应使用“ $ first”累加器完成。我们使用$$ROOT保留整个文档。 然后,可以用组中的文档替换根文档。

分组不会保留任何顺序,因为要对最终结果进行排序,因此需要再次排序。

实现此目标的mongo shell代码如下所示:

db.getCollection('operationData').aggregate([
{ $match: ... } ,
{ $project: { amount: 1, operationId: 1 } },
{ $sort: { amount: -1 } },
{ $group: { _id: '$operationId', g: { $first: {data: '$$ROOT'} }} },
{ $replaceRoot: { newRoot: '$g.data' }},
{ $sort: { amount: 1 } }
])

这将需要翻译成Spring Data Mongo(也许我以后会花时间尝试一下)。