将$ strLenCP与Spring Data MongoDB一起使用

时间:2017-01-09 14:41:47

标签: mongodb spring-data aggregation-framework

我有这个mongodb查询

db.getCollection('myCollection').aggregate(
    [{
        $project: {
            length: {
                $strLenCP: "$prefix"
            }
        }
    }, {
        $sort: {
            length: -1
        }
    }]
)

我想在spring java项目中使用但是我无法编写正确的java代码(排序不是问题)。

我试过这个

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(调试模式)中得到一个空键:

{
    "aggregate": "__collection__",
    "pipeline": [{
        {
            "$project": {
                "prefixLength": {
                    "null": ["$prefix"]
                }
            }
        }]
    }
}

我可以看到我的agg对象有这个投影操作:

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

有人可以帮忙吗?

干杯

3 个答案:

答案 0 :(得分:2)

在1.10.0.RC1中添加了对Mongo3.4聚合运算符的支持。如果你可以更新到发布候选版本,一切都应该正常工作。

或者您可以尝试以下操作,但您需要使用1.8.5版本。

 Aggregation aggregation = newAggregation(
  project().and(new AggregationExpression() {
      @Override
      public DBObject toDbObject(AggregationOperationContext aggregationOperationContext) {
          return new BasicDBObject("$strLenCP", "$prefix");
      }
  }).as("prefixLength")
 );

答案 1 :(得分:0)

您可以使用表达式project(...).and(valueOf("fieldName").lengthCP()).as("fieldLength")

答案 2 :(得分:0)

@kairius的答案尚不清楚。这是应该这样做的方式:使用StringOperators#valueOf,然后使用lengthCP()

TypedAggregation.project()
    .and(StringOperators.valueOf("prefix").lengthCP())
    .as("length")