Get result from all mongodb documents

Viewed 52

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.

1 Answers

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.*"
            }
          }
        }
      }
    }
  }
])
Related