我最近开始使用SpringData探索MongoDB中的Aggregation Framework。我可以创建以下查询,即
db.consumer_order.aggregate([ { $match: {_id: ObjectId("59e43f542397a00de0c688e4"), "orderState":"Confirmed"}}, { $project: { parts: {$filter: { input: '$parts', as: 'item', cond: {$eq: ['$$item.currentState', "Estimation Confirmed"]} }} }} ])
Spring在MongoDB Native Driver中使用以下代码
List<Document> aggrigationList = new ArrayList<>(); List<String> conditions = new ArrayList<>(); conditions.add("$$item.currentState"); conditions.add("Estimation Confirmed"); Document matchDoc = new Document("$match",new Document("_id",new ObjectId(orderId))); Document projectDoc = new Document("$project",new Document("parts",new Document("$filter",new Document("input","$parts").append("as", "item").append("cond", new Document("$eq",conditions))))); aggrigationList.add(matchDoc); aggrigationList.add(projectDoc); Document orderWithPendingParts = consumerOrderCollection.aggregate(aggrigationList).first();
但我确实知道始终与本机驱动程序一起工作不是一个好习惯,因为我们已经掌握了Spring-Data。但是我无法使用Spring Data将上述MongoDB查询构造到AggrigationObject。我尝试了以下内容,但是在构造 Aggregation.project()时 遇到困难,即
mongoTemplate.aggregate(Aggregation.newAggregation( Aggregation.match(Criteria.where("owner").is(user).andOperator(Criteria.where("orderState").is("confirmed"))), ***Finding Difficulty in here*** ), inputType, outputType)
指导我,如果我做错了什么。
您可以尝试下面的查询。
静态进口
import static org.springframework.data.mongodb.core.aggregation.Aggregation.*; import static org.springframework.data.mongodb.core.aggregation.ArrayOperators.Filter.filter; import static org.springframework.data.mongodb.core.aggregation.ComparisonOperators.Eq.valueOf;
码
Aggregation aggregation = newAggregation( project().and(filter("parts") .as("item") .by(valueOf( "item.currentState") .equalToValue( "Estimation Confirmed"))) .as("parts"); ); List<outputType> results = mongoTemplate.aggregate(aggregation, inputType, outputType)