[英]Does Spring Data MongoDb support $filter array aggregations operator?
[英]Sum Aggregations in MongoDB Using Spring Data
這是我的數據
{"intentId" : "A1", "like" : "Y"}
{"intentId" : "A1", "like" : "Y"}
{"intentId" : "A1", "like" : "N"}
{"intentId" : "A2", "like" : "Y"}
{"intentId" : "A2", "like" : "N"}
{"intentId" : "A2", "like" : "N"}
{"intentId" : "A2", "like" : "N"}
和mondodb腳本運行非常好。 這是代碼。
db.getCollection('test').aggregate( [
{
$project:
{
intentId: 1,
likeY:
{
$cond: [ { $eq: [ "$like", "Y" ] }, 1, 0 ]
},
likeN:
{
$cond: [ { $eq: [ "$like", "N" ] }, 1, 0 ]
}
}
},
{ $group : { _id : "$intentId", likeY: { $sum: "$likeY" }, likeN: { $sum: "$likeN" } }}
] );
我的問題是我想在spring數據下運行此代碼
MatchOperation matchStage = Aggregation.match(new Criteria ("delYn").ne("Y"));
GroupOperation groupStage = Aggregation.group("intentId");
Cond operatorNbS = ConditionalOperators.when("like").then("Y").otherwise(value)
ProjectionOperation projectStage = Aggregation.p
SortOperation sortStage = Aggregation.sort(Sort.Direction.DESC, "_id");
Aggregation aggregation = Aggregation.newAggregation(matchStage, groupStage,projectStage,sortStage);
請給我一些解決我的問題的技巧。...在此先謝謝您!
到目前為止,還沒有辦法用Spring做到這一點。 嘗試改用DBOject。
public static AggregationOperation projectLikeNY() {
DBObject projectYN = new BasicDBObject("$project", new BasicDBObject("intentId", 1).append("likeY", new BasicDBObject("$cond", Arrays. < Object > asList(new BasicDBObject("$eq", Arrays. < Object > asList("$like", "Y")),
1, 0))).append("likeN", new BasicDBObject("$cond", Arrays. < Object > asList(new BasicDBObject("$eq", Arrays. < Object > asList("$like", "N")),
1, 0)))
);
CustomAggregationOperation project= new CustomAggregationOperation(
projectYN);
return project;
}
在項目中的某個位置創建以下CustomAggregationOperation:
public class CustomAggregationOperation implements AggregationOperation {
private DBObject operation;
public CustomAggregationOperation(DBObject operation) {
this.operation = operation;
}
@Override
public DBObject toDBObject(AggregationOperationContext context) {
return context.getMappedObject(operation);
}
}
代替使用ProjectionOperation,使用以下命令:
AggregationOperation projectStage = projectLikeNY();
Aggregation aggregation = Aggregation.newAggregation(matchStage, groupStage,projectStage,sortStage);
希望這可以幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.