使用带有Spring-data-mongodb的$ cond运算符

ltf*_*hie 2 mongodb aggregation-framework spring-data-mongodb

我希望汇总以下数据

{
   "user": "user1",
   "error": true 
}
{
   "user": "user2",
   "error": false
}
{
   "user": "user1",
   "error": false
}
Run Code Online (Sandbox Code Playgroud)

{
     "_id": "user1",
     "errorCount": 1,
     "totalCount": 2
},
{
     "_id": "user2",
     "errorCount": 0,
     "totalCount": 1
}
Run Code Online (Sandbox Code Playgroud)

使用$ cond运算符,可以使用以下方法实现:

$group: {
    _id: "$user",
    errorCount : { "$sum" : {"$cond" : ["$error", 1, 0]}},
    totalCount : { "$sum" : 1 }
}
Run Code Online (Sandbox Code Playgroud)

但是,由于我使用的是Spring-data-mongodb,它还不支持$ cond(从1.3.4-RELEASE开始),我无法做到这一点.

有没有办法在没有$ cond的情况下进行相同的聚合?

ltf*_*hie 7

感谢Neil Lunn的建议,我设法让$ cond使用spring-data的聚合支持.为此,您必须实现AggregationOperation接口以接收DBObject.

public class DBObjectAggregationOperation implements AggregationOperation {
  private DBObject operation;

  public DBObjectAggregationOperation (DBObject operation) {
    this.operation = operation;
  }

  @Override
  public DBObject toDBObject(AggregationOperationContext context) {
    return context.getMappedObject(operation);
  }
}
Run Code Online (Sandbox Code Playgroud)

然后你就可以在TypeAggregation中正常使用它了:

DBObject operation = (DBObject)JSON.parse ("your pipleline here...");
TypedAggregation<UserStats> aggregation = newAggregation(User.class,
    new DBObjectAggregationOperation(operation)
    );
AggregationResults<UserStats> result = mongoTemplate.aggregate(aggregation, UserStats.class); 
Run Code Online (Sandbox Code Playgroud)

此方法将允许您使用框架中尚未定义的任何聚合运算符.但是,它也绕过了弹簧数据的验证,应谨慎使用.
如果您希望通过该框架正确支持$ cond运算符,请投票:https://jira.springsource.org/browse/DATAMONGO-861