Regex 检查字段是否包含字符串列表中的值
我需要准备一个查询,该查询将运行regex来检查包含的结果。 我收集了两份员工ID文件:Rabin和Begin 我想查找包含列表(“ab”、“it”)的员工姓名的文档。相关mongo查询:Regex 检查字段是否包含字符串列表中的值,regex,mongodb,scala,Regex,Mongodb,Scala,我需要准备一个查询,该查询将运行regex来检查包含的结果。 我收集了两份员工ID文件:Rabin和Begin 我想查找包含列表(“ab”、“it”)的员工姓名的文档。相关mongo查询: db.tasks.find( { employeeId : {$in : [/ab/, /it/]} } ) 它返回一个employeeId为“Rabin”的结果文档。 问题是如何将此查询转换为Scala代码?我已经实现了以下测试代码: val fieldName: String =
db.tasks.find( { employeeId : {$in : [/ab/, /it/]} } )
它返回一个employeeId为“Rabin”的结果文档。
问题是如何将此查询转换为Scala代码?我已经实现了以下测试代码:
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")
})
但是获取异常的结果会被抛出。。
打印件:
formattedVals: List(/ab/, /it/)
{
'employeeId': {
'$in': [
'/ab/',
'/it/'
]
}
}
在“斜杠”参数周围加上单引号的mongo查询不会返回任何结果。
有没有关于如何在Scala中实现所需查询的想法?您可以按如下方式执行:
val formattedVals = value.map(value => s"(.*)$value(.*)").mkString("|")
并使用$regex
(而不是$in
)
例如,在您的情况下:
val mySelector = BSONDocument(fieldName -> BSONDocument("$regex" -> formattedVals))
val mySelector = BSONDocument(fieldName -> BSONDocument("$not" -> BSONDocument("$regex" -> formattedVals)))
非常神奇,谢谢@Zvi Mints