首页 文章

Spring Data MongoDB:在多个字段中搜索

提问于
浏览
0

我有一个包含User对象的MongoDB集合,其中包含两个字段:Firstname和Lastname . 我需要一个只需要一个字符串(代表用户全名)的查询来进行findLike研究 .

问题与question相同,但我不知道如何使用MongoTemplate或@Query注释转换Spring数据中的MongoDB存储库查询

编辑:使用项目运算符我必须指定我想要包含在阶段中的所有字段 . 一个更好的解决方案可能是使用 AddFields operator:我发现的类似问题是:https://stackoverflow.com/a/40812293/6545142

如何在MongoTemplate中使用 $AddFields 运算符?

1 回答

  • 4

    您可以使用$expr(3.6 mongo版本运算符)在常规查询中使用聚合函数,仅用于完全匹配 .

    Spring @Query 代码

    @Query("{$expr:{$eq:[{$concat:["$Firstname","$Lastname"]}, ?0]}}")
    ReturnType MethodName(ArgType arg);
    

    对于查找搜索或精确搜索,您需要在较低版本中通过mongo模板使用聚合 .

    AggregationOperation project = Aggregation.project().and(StringOperators.Concat.valueOf("Firstname").concatValueOf("Lastname")).as("newField");
    

    for like matches

    AggregationOperation match = Aggregation.match(Criteria.where("newField").regex(val));
    

    for exact match

    AggregationOperation match = Aggregation.match(Criteria.where("newField").is(val));
    

    其余的代码

    Aggregation aggregation = Aggregation.newAggregation(project, match);
     List<BasicDBObject> basicDBObject =  mongoTemplate.aggregate(aggregation, colname, BasicDBObject.class).getMappedResults();
    

相关问题