Spring 数据MongoDB: 在多个字段上进行类似搜索

Spring Data MongoDB: search like on multiple fields

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

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

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

如何将 $AddFields 运算符与 MongoTemplate 一起使用?

您可以使用 $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();