How do I write a query for mongodb using the casbah driver for scala that uses a substring and checks if the field is in a list of supplied values?

StackOverflow https://stackoverflow.com/questions/19126471

Domanda

Say I have a table in mongodb with a data structure that looks like this:

{
    _id: "123456",
    provider: "apple",
    languageCode: "en-US",
    data: "some data"
}

How would I write my query so that i retrieve entries whose FULL language codes OR a sub-string of that language code (2 characters) are in my languageCodeFilter string list? So if an entry's languageCode is either "en-US" or "en-CA", it will match because i have "en" in my filter. if an entry has "fr" or "fr-FR" it will NOT be returned because i'm only asking for "fr-CA".

val provider: String = "apple"
val languageCodeFilter : List[String] = List("en", "fr-CA", "it")
val query: DBObject = MongoDBObject("provider" -> provider
  , /* what do i put here? */)
È stato utile?

Soluzione

You can build a regex. I don't have my environment up to test it, but this should help you get on track:

import com.mongodb._
val regex = languageCodeFilter map ( l => s"(?:.*\\Q$l\\E.*)" ) mkString "|" r
val query = QueryBuilder.start("languageCode").regex(regex).get
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top