0

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?

Emanuele Vannacci
  • 321
  • 1
  • 6
  • 15

1 Answers1

4

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();
s7vr
  • 73,656
  • 11
  • 106
  • 127
  • It works but returns me an object with all attributes set on null, only the Id is set... – Emanuele Vannacci Feb 02 '18 at 20:01
  • Add all the fields in the project stage that you need to keep in the response. Something like `project("field1", "field2")`. Change to your pojo class from BasicDBObject for mapping – s7vr Feb 02 '18 at 21:36
  • My pojo class has really many attributes, and adding all the fields in the project stage is not very nice. I found a better solution with $addFields operator instead of project. My query looks like: `{$addFields: {'newField': {$concat:["$field1"," ","$field2"]} } }, {$match: {'newField':'value'}}` . How can I use it with MongoTemplate? – Emanuele Vannacci Feb 02 '18 at 22:13
  • I wanted to suggest that but there is no helper for addFields just yet and wanted to know what your requirement was. So just need to use AggregationOperation to create a new stage. [Here](https://stackoverflow.com/q/43326515/2683814) is such example. – s7vr Feb 02 '18 at 23:18
  • Thank you! Through AggregationOperation I create the addFileds operator, and now it works properly – Emanuele Vannacci Feb 03 '18 at 13:27