Necesito preparar una consulta que ejecutará expresiones regulares para verificar si contiene resultados. Tengo dos documentos en la colección con employeeIds: Rabin y Begin. Quiero encontrar documentos con el nombre del empleado que contenga List("ab", "it"). La consulta mongo relevante:
db.tasks.find( { employeeId : {$in : [/ab/, /it/]} } )Devuelve un documento de resultado con employeeId de "Rabin". La pregunta es ¿cómo estoy convirtiendo esta consulta en código Scala? He implementado el siguiente código de prueba:
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") })PERO se arroja el resultado de la excepción ... Las salidas impresas:
formattedVals: List(/ab/, /it/) { 'employeeId': { '$in': [ '/ab/', '/it/' ] } }La consulta mongo con comillas simples alrededor de los parámetros "recortados" no devuelve ningún resultado. ¿Alguna idea de cómo implementar la consulta requerida en Scala?
Puedes hacerlo de la siguiente manera:
val formattedVals = value.map(value => s"(.*)$value(.*)").mkString("|") y use $regex (en lugar de $in )
Por ejemplo, en tu caso:
val mySelector = BSONDocument(fieldName -> BSONDocument("$regex" -> formattedVals)) val mySelector = BSONDocument(fieldName -> BSONDocument("$not" -> BSONDocument("$regex" -> formattedVals)))