0

In our spring Boot application using mongotemplate, I need to write a query to get the results using LIKE operator. But in mongotemplate just like in SQL, I don't have a direct query which I can use.

I have tried with some of the options like Aggregate and regex methods but it didn't work.

In MongoDB tried the same.

db.getCollection('Months').find({"name":/Jan/}).

So in the months table, I have to retrieve results that contains 'Jan' letters in the column 'name'. But on running this query suppose I have an entry called 'DecJan' in that Case I am not able to retrieve it.

Query constantQuery = new Query();``
constantQuery.addCriteria(Criteria.where("name").regex("DecJan", "i"));

List<Months> pp = this.mongoTemplate.find(constantQuery, Months.class);

So, the expected is If I have two entries in a table like 'January','DecJan' And in a query, if I pass 'Jan', I need to retrieve both the results using mongotemplate.

Mustahsan
  • 3,852
  • 1
  • 18
  • 34
Mohan Kumar
  • 29
  • 1
  • 4
  • Possible duplicate of [How to query MongoDB with "like"?](https://stackoverflow.com/questions/3305561/how-to-query-mongodb-with-like) – pvpkiran Oct 10 '19 at 10:15

1 Answers1

0

The duplication link updated does not refer to the mongoTemplate instance which is required..

By the way i have used aggregationOperation for the same and got the results.

  1. Creating AggregationOperation
  2. Build Aggreation Object with the match required.
  3. query with Mongotemplate.aggregate(AggregationOperation,Aggreation)

Sample code: AggregationOperation aggregate = Aggregation.project().and("FirstName").as("name");

        AggregationOperation operation = Aggregation.match(Criteria.where("name").regex(pattern, "i"));

        Aggregation aggregation = Aggregation.newAggregation(aggregate, operation);

Now able to retrieve the results.

Mohan Kumar
  • 29
  • 1
  • 4