我希望汇总以下数据
{
"user": "user1",
"error": true
}
{
"user": "user2",
"error": false
}
{
"user": "user1",
"error": false
}
进入
{
"_id": "user1",
"errorCount": 1,
"totalCount": 2
},
{
"_id": "user2",
"errorCount": 0,
"totalCount": 1
}
使用 $cond 运算符,这可以通过以下方式实现:
$group: {
_id: "$user",
errorCount : { "$sum" : {"$cond" : ["$error", 1, 0]}},
totalCount : { "$sum" : 1 }
}
但是,由于我使用的 Spring-data-mongodb 尚不支持 $cond(自 1.3.4-RELEASE 起),因此我无法执行此操作。
有没有办法在没有 $cond 的情况下进行相同的聚合?
感谢 Neil Lunn 的建议,我已经设法让 $cond 使用来自 spring-data 的聚合支持。为此,您必须实现 AggregationOperation 接口(interface)以接收 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);
}
}
然后就可以在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);
这种方法将允许您使用框架中尚未定义的任何聚合运算符。但是,它也绕过了 spring-data 进行的验证,应谨慎使用。
如果您希望通过框架正确支持 $cond 运算符,请投票:https://jira.springsource.org/browse/DATAMONGO-861