Checking if a field contains a value from list of strings

Viewed 454

I need to prepare a query that will run regex to check for contains results. I have two docs in collection with employeeIds: Rabin and Begin I want to find documents with employee name that contains List("ab", "it"). The relevant mongo query:


    db.tasks.find( { employeeId : {$in : [/ab/, /it/]} } )

It returns a result document with employeeId of "Rabin". The question is how i'm converting this query into Scala code? I have implemented the following test code:


    val fieldName: String = "employeeId"
        val value: List[String] = List("ab", "it")
        val formattedVals = value.map ("/".concat(_).concat("/"))
        val mySelector = BSONDocument(fieldName -> BSONDocument("$in" -> formattedVals))
        println(s"formattedVals: $formattedVals")    
        println(BSONDocument.pretty(mySelector))
    
        collection.findAndUpdate(
          selector = mySelector,
          update = BSONDocument("$set" ->BSONDocument(
            "CompanyId" -> "1000")),
          fetchNewObject = true
        ).map(el => el.result[GatorTask].getOrElse {
          throw new NoSuchElementException(s"No Document was found to match the query")
        })

BUT getting the result of exception is thrown .. The print outs:


    formattedVals: List(/ab/, /it/)
    {
      'employeeId': {
        '$in': [
          '/ab/',
          '/it/'
        ]
      }
    }

The mongo query with single quotes around "slashed" parameters returns no result. Any ideas how to implement the required query in Scala?

1 Answers

You can do it as follows:

val formattedVals = value.map(value => s"(.*)$value(.*)").mkString("|")

and use $regex (Instead of $in)

For example, in your case:

val mySelector = BSONDocument(fieldName -> BSONDocument("$regex" -> formattedVals))

val mySelector = BSONDocument(fieldName -> BSONDocument("$not" -> BSONDocument("$regex" -> formattedVals)))
Related