【问题标题】:Use $strLenCP with Spring Data MongoDB将 $strLenCP 与 Spring Data MongoDB 一起使用
【发布时间】:2017-01-09 14:41:46
【问题描述】:

我有这个 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

有人可以帮忙吗?

干杯

【问题讨论】:

  • 感谢@Sagar Reddy 格式化
  • Np。你在哪个版本的 spring-mongo-db 上?
  • mongo-java-driver 版本是 3.4.0 和 org.springframework.data 是 1.9.5.RELEASE

标签: mongodb spring-data aggregation-framework


【解决方案1】:

在 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.10.0 RC1 将聚合运算符添加为 API,并通过 SpEL support 公开多个聚合表达式。
  • 非常感谢@Sagar Reddy,DBObject 解决方案完美运行。我不能使用 RC,因为我正在编写的代码很快就会在生产中使用,但我会在可用时更新
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    @kairius 的回答不清楚。应该这样做:使用StringOperators#valueOf,后跟lengthCP()

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

    【讨论】:

      猜你喜欢
      • 2014-10-21
      • 2017-11-07
      • 2017-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-10
      • 2017-05-20
      相关资源
      最近更新 更多