【问题标题】:MongoDB criteria with $trim using MongoTemplate使用 MongoTemplate 的带有 $trim 的 MongoDB 条件
【发布时间】:2023-01-11 13:40:05
【问题描述】:

我正在尝试使用 MongoTemplate 和 Criteria 以及 Trim 函数在 Mongo 集合中的字段值上为以下 MongoDB 命令编写 Java 代码

db.employees.aggregate([
     {
        $match : {$expr: {$eq: [{ $trim: {input: "empName"}}, "John Smith"]}}
     }
])

我可以看到我们在弹簧数据-mongodb包含返回 Trim 类实例的 trim() 函数的 jar,但我找不到将其与 Criteria 或 AggregationExpression 一起使用的方法,我可以将其与 mongoTemplate.aggregate() 一起使用

附言我可以实现相同的使用Mongo 集合通过构建 org.bson.Document 列表并简单地调用类似的方法,但我希望使用 mongoTemplate.aggregate() 本身实现相同

List<Document> pipelineDocumentList = constructPipelineDocument(empName);
mongoTemplate.getCollection("employees").aggregate(pipelineDocumentList, Employee.class)

【问题讨论】:

    标签: mongodb spring-data-mongodb mongotemplate spring-mongodb


    【解决方案1】:
    AggregationOperation matchStage = Aggregation.match(
            EvaluationOperators.valueOf(
                    Eq.valueOf(
                            Trim.valueOf("empName")
                    ).equalToValue("John Smith")
            ).expr()
    );
    
    List<Employee> e = mongoTemplate.aggregate(
        Aggregation.newAggregation(matchStage),
        Employee.class,
        Employee.class
    )
    .getMappedResults();
    

    【讨论】:

      猜你喜欢
      • 2015-01-08
      • 2015-10-16
      • 2017-03-02
      • 1970-01-01
      • 1970-01-01
      • 2023-02-13
      • 2016-11-12
      • 1970-01-01
      • 2023-03-11
      相关资源
      最近更新 更多