1

I have a document

[
    {
      "contentId": "62738f2fba6155003dd1e25d",
      "tags": [
        "spring boot",
        "spring jpa"
      ]
      
    },
    {
      "contentId": "62738f98ba6155003dd1e25e",
  
      "tags": [
        "spring",
        "java"
      ]
    }
]

I need to write a @Query expression in spring jpa to get the results with tags that matches the regex '.spr.'. So, the expected result would be a set of all matching tags.

[spring, spring boot, spring jpa]

I tried to write like

    @Query(value = "{tags : { '$regex' : ?0 , $options: 'i'}}", fields = "{tags : 1,_id : 0}")
Set<String> findByTags(String tag);

but that gives me all matched tags documents.

Please help me to get an array of matched texts.

Achyut
  • 377
  • 1
  • 3
  • 17

1 Answers1

1

You can use $filter from aggregation framework to get only matching array elements.

playground

db.collection.aggregate([
  {
    $project: {
      d: {
        $filter: {
          input: "$tags",
          as: "num",
          cond: {
            $regexMatch: {
              input: "$$num",
              regex: ".*spr.*"
            }
          }
        }
      }
    }
  }
])
Gibbs
  • 21,904
  • 13
  • 74
  • 138
  • My expected result is [spring, spring boot, spring jpa], can we achieve this in spring-mongorepository – Achyut May 05 '22 at 16:35
  • [Refer this answer for spring mongorepo example](https://stackoverflow.com/questions/59697496/how-to-do-a-mongo-aggregation-query-in-spring-data) Yes you can achieve that. I suggest you to give a try and post a new question – Gibbs May 05 '22 at 16:41
  • 1
    I updated the query to "{ $project : { d : { $filter : { input : '$tags', as : 'num', cond : { $regexMatch : { input : '$$num', regex : ?0, options : 'i'}}}}}}", "{ $unwind : { path : '$d'}}", "{ $group : { _id : { id : '$id'}, tags : { $addToSet : '$d'}}}", "{ $project : { _id : 0, tags : 1}}" and I got the expected results. I am not able to update the answer due to error "Suggested edit queue is full". Thanks for the quick response. – Achyut May 09 '22 at 14:45