【问题标题】:Using $cond operator with Spring-data-mongodb [duplicate]将 $cond 运算符与 Spring-data-mongodb 一起使用 [重复]
【发布时间】:2014-02-25 17:15:36
【问题描述】:

我希望汇总以下数据

{
   "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 的情况下进行相同的聚合?

【问题讨论】:

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


    【解决方案1】:

    感谢 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);
      }
    }
    

    那么你就可以在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

    【讨论】:

      【解决方案2】:

      即使 Spring 数据中还没有“函数式接口”,您也不必为此绑定。 (顺便说一句,提出一个 JIRA)

      只需获取本机表单并在管道中使用 BasicDBObject 类型。所以原则上:

          DBCollection myCollection = mongoOperation.getCollection("collection");
      
          <result cast> = myCollection.aggregate(<pipeline here>);
      

      Spring 数据为您提供抽象,但它禁止使用 本机 驱动程序函数。它实际上为您提供了访问器来使用它们,正如我在上面演示的那样。

      【讨论】:

      • 是的,在这种情况下使用本机界面会容易得多。我希望有一种方法可以直接将布尔值转换为整数值。
      • @ltfishie aggregation framework operators 中没有强制转换运算符。唯一的例外是$substr,它将整数转换为字符串。在这种情况下,$cond 测试是执行此操作的有效方法。
      猜你喜欢
      • 1970-01-01
      • 2014-10-21
      • 2017-11-07
      • 1970-01-01
      • 2017-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多