Search code examples
scalareactivemongo

Find all names in a mongoDB containing a given substring


Hi there I am using scala and play2-reactivemongo version 0.16.2-play26. I want to be able to do a search query on a json collection where all names will be returned that contain a given substring. I have come across using $text with indexes but I am not sure how to set this up in the version of reactivemongo I am using. Is $text supposed to be declared in my code?

Does any have an example that is written in Scala?

Many thanks


Solution

  • Thank you @cchantep :)

    I managed to solve this problem with this code:

    def searchItem(name: String): Future[List[Item]] =
      jsonCollectionFuture.flatMap(
        _.find(Json.obj("name" -> Json.obj("$regex" -> (".*" + name + ".*"))), None)
          .cursor[Item](ReadPreference.Primary)
          .collect[List](-1, Cursor.FailOnError[List[Item]]())
      )