繁体   English   中英

使用Spring数据在MongoDB中进行汇总汇总

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM