【问题标题】:Sum Aggregations in MongoDB Using Spring Data使用 Spring Data 在 MongoDB 中求和聚合
【发布时间】:2017-07-28 04:55:47
【问题描述】:

这是我的数据

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

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

【问题讨论】:

  • 我无法处理提交的条件。

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


【解决方案1】:

到目前为止,还没有办法用 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);

希望对你有帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-02
    • 2014-01-30
    • 2019-11-27
    • 1970-01-01
    相关资源
    最近更新 更多