在Spring Mongo中使用$ stdDevSamp或$ stdDevPop [英] Use $stdDevSamp or $stdDevPop with Spring Mongo
问题描述
我想知道如何实现在Spring Mongo Data中使用的标准偏差聚合函数.
I'd like to know how to implement a Standard Deviation aggregation Function to use in Spring Mongo Data.
我知道Mongo DB 3.2具有标准偏差聚合功能,但是在Spring Data中不可用.
I Know Mongo DB 3.2 has a Standard Deviation aggregation function, but It isn't available in Spring Data.
我可以使用Mongo的汇总功能吗?
Could I use the Mongo's aggregation function?
谢谢.
推荐答案
不可用" 和未实现辅助方法" 之间有明显的区别,这就是实际情况.只是因为没有用于实现 $stdDevSamp
的帮助器"或 $stdDevPop
运算符,并不意味着它们无法使用,当然,只要您连接到MongoDB 3.2实例即可.
There is a distinct difference between "not available" and "no implemented helper method", and that is the real case here. Just because there is no "helper" for implementing the $stdDevSamp
or $stdDevPop
operators, does not mean they cannot be used, as long as you are connecting to a MongoDB 3.2 instance of course.
您真正需要的是一个支持AggregationOperation
接口的自定义类,该类允许使用DBObject
进行构造:
All you really need is a custom class supporting the AggregationOperation
interface, that will allow construction using 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);
}
}
然后您可以在聚合管道构建中使用该类,如下所示:
Then you can use that class in aggregation pipeline construction like so:
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"))
)
)
);
这相当于文档示例 :
db.users.aggregate(
[
{ "$sample": { "size": 100 } },
{ "$group": { "_id": null, "ageStdDev": { "$stdDevSamp": "$age" } } }
]
)
作为AggregationOperation
的接口,该类可以轻松地与已实现的帮助程序混合:
As an interface for AggregationOperation
the class easily mixes with the implemented helpers:
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"))
)
)
);
因此,即使没有帮手",您仍然可以使用功能来为您制定BSON对象构造.您只需要自己进行构建即可.
So you can still use features even if there is no "buit in helper" to work out the BSON Object construction for you. You just do the construction yourself.
这篇关于在Spring Mongo中使用$ stdDevSamp或$ stdDevPop的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!