使用Spring数据的MongoDB中的Sum聚合

时间:2017-07-28 04:55:48

标签: java mongodb mongodb-query spring-data aggregation-framework

这是我的数据

{"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);

请给我一个提示来解决我的问题.... 提前谢谢!

1 个答案:

答案 0 :(得分:0)

到目前为止,没有办法用春天来做。请尝试使用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);

希望这有帮助