0
votes

I have a MongoDB collection containing User objects with two fields: Firstname and Lastname. I need a query that takes only one string (representing the user fullname) for a findLike research.

The problem is the same of this question but I do not know how translate that query for a MongoDB Repository in Spring Data using MongoTemplate or @Query annotation

EDIT: Using project operator i have to specify all fields I want include in the stages. A better solution maybe could be use AddFields operator: A similar question I found is that: https://stackoverflow.com/a/40812293/6545142

How can I use the $AddFields operator with MongoTemplate?

1
What is your mongo version ? You can check running db.version() in shell. - s7vr
@Veeram the version is 3.4.10 - Emanuele Vannacci

1 Answers

4
votes

You can use $expr ( 3.6 mongo version operator ) to use aggregation functions in regular query for only exact matches.

Spring @Query code

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

For find like searches or exact search you've to use aggregation via mongo template in lower versions.

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

Rest of the code

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