gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 07:34:25 25 4
gpt4 key购买 nike

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

我知道 Mongo DB 3.2 有标准偏差聚合功能,但 Spring Data 中不提供该功能。

我可以使用Mongo的聚合功能吗?

谢谢。

最佳答案

“不可用”和“没有实现的辅助方法”之间有明显的区别,这就是这里的真实情况。只是因为没有“ helper ”来实现$stdDevSamp$stdDevPop运算符,并不意味着它们不能使用,当然只要您连接到 MongoDB 3.2 实例即可。

您真正需要的是一个支持 AggregationOperation 接口(interface)的自定义类,该类将允许使用 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);
}
}

然后您可以在聚合管道构造中使用该类,如下所示:

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的接口(interface),该类可以轻松地与实现的帮助器混合:

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 对象,您仍然可以使用功能。您只需自己构建即可。

关于java - 将 $stdDevSamp 或 $stdDevPop 与 Spring Mongo 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35605815/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com