将 $strLenCP 与 Spring Data MongoDB 一起使用 [英] Use $strLenCP with Spring Data MongoDB
问题描述
我有这个 mongodb 查询
I have this mongodb query
db.getCollection('myCollection').aggregate(
[{
$project: {
length: {
$strLenCP: "$prefix"
}
}
}, {
$sort: {
length: -1
}
}]
)
我想在 Spring Java 项目中使用,但我无法编写正确的 Java 代码(排序不是问题).
that I want to use into a spring java project but I can't manage to write the correct java code (the sort is not the issue).
我试过了
Aggregation agg = newAggregation(project().andExpression("strLenCP(prefix)").as("prefixLength"));
AggregationResults < RequestSettingsWithPrefixLength > results = mongoTemplate.aggregate(agg, RequestSettings.class, RequestSettingsWithPrefixLength.class);
List < RequestSettingsWithPrefixLength > requestSettingsList = results.getMappedResults();
但我在 agg JSON(调试模式)中得到一个空键:
but I am getting a null key in agg JSON (debug mode):
{
"aggregate": "__collection__",
"pipeline": [{
{
"$project": {
"prefixLength": {
"null": ["$prefix"]
}
}
}]
}
}
可以看到我的agg对象有这个投影操作:
I can see that my agg object has this projection operation:
expression -> strLenCP(prefix)
field -> AggregationField: AggregationField - name: prefixLength, target: prefixLength, synthetic: true
params -> []
我不确定这是否正确,但我找不到任何使用 strLenCP 的文档.我只发现这个使用 strLenCP 投影的测试:https://github.com/spring-projects/spring-data-mongodb/blob/dc57b66adfd60b4d69d1d349b4fcfa4ab0da95e7/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/aggregation/SpelExpressionTransformerUnitTests.java#L922
I am not sure this is correct but I can't find any documentation that uses strLenCP. I only found this test that uses the strLenCP projection: https://github.com/spring-projects/spring-data-mongodb/blob/dc57b66adfd60b4d69d1d349b4fcfa4ab0da95e7/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/aggregation/SpelExpressionTransformerUnitTests.java#L922
有人可以帮忙吗?
干杯
推荐答案
在 1.10.0.RC1 中增加了对 Mongo3.4 聚合算子的支持.如果您可以更新到发布候选版本,一切都应该可以正常工作.
The support for Mongo3.4 aggregation operators were added in 1.10.0.RC1. If you are okay with updating to release candidate version everything should just work fine.
或者您可以尝试以下方法,但您需要使用 1.8.5 版本.
Or you can try the following but you'll need to use 1.8.5 version.
Aggregation aggregation = newAggregation(
project().and(new AggregationExpression() {
@Override
public DBObject toDbObject(AggregationOperationContext aggregationOperationContext) {
return new BasicDBObject("$strLenCP", "$prefix");
}
}).as("prefixLength")
);
这篇关于将 $strLenCP 与 Spring Data MongoDB 一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!