Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

174
Views
Checking if a field contains a value from list of strings

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?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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)))
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!