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

时间:2018-02-02 15:48:28

标签: java mongodb mongodb-query spring-data spring-data-mongodb

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

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

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

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

1 个答案:

答案 0 :(得分: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");

匹配

AggregationOperation match = Aggregation.match(Criteria.where("newField").regex(val));
完全匹配

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();