将 $stdDevSamp 或 $stdDevPop 与 Spring Mongo 一起使用

Use $stdDevSamp or $stdDevPop with Spring Mongo

我想知道如何实现标准偏差聚合函数以在 Spring Mongo 数据中使用。

我知道 Mongo DB 3.2 有一个标准偏差聚合函数,但它在 Spring 数据中不可用。

我可以使用Mongo的聚合函数吗?

谢谢。

"not available""no implemented helper method"之间有明显的区别,这就是这里的真实情况.仅仅因为没有 "helper" 用于实现 $stdDevSamp or $stdDevPop 运算符,并不意味着它们不能使用,当然只要您连接到 MongoDB 3.2 实例。

你真正需要的是一个支持 AggregationOperation 接口的自定义 class,这将允许使用 DBObject:

进行构建
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);
    }
}

然后你可以像这样在聚合管道构造中使用那个class:

Aggregation aggregation = newAggregation(
    new CustomAggregationOperation(
        new BasicDBObject("$sample", new BasicDBObject("size",100))
    ),
    new CustomAggregationOperation(
        new BasicDBObject(
            "$group",
            new BasicDBObject("_id",null)
                .append("ageStdDev",new BasicDBObject("$stdDevSamp","$age"))
        )
    )
);

这相当于 documentation example:

db.users.aggregate(
   [
      { "$sample": { "size": 100 } },
      { "$group": { "_id": null, "ageStdDev": { "$stdDevSamp": "$age" } } }
   ]
)

作为 AggregationOperation 的接口,class 可以轻松地与已实现的助手混合使用:

Aggregation aggregation = newAggregation(
    // Using the match helper for the `$match` stage
    match(
        Criteria.where("age").gte(20).lte(50)
    ),
    // Mixed in with custom classes for the others
    new CustomAggregationOperation(
        new BasicDBObject("$sample", new BasicDBObject("size",100))
    ),
    new CustomAggregationOperation(
        new BasicDBObject(
            "$group",
            new BasicDBObject("_id",null)
                .append("ageStdDev",new BasicDBObject("$stdDevSamp","$age"))
        )
    )
);

因此,即使没有 "buit in helper" 为您计算出 BSON 对象构造,您仍然可以使用功能。你自己施工就行了。