【问题标题】:Checking if a field contains a value from list of strings检查字段是否包含字符串列表中的值
【发布时间】:2021-01-18 00:34:47
【问题描述】:

我需要准备一个查询,该查询将运行正则表达式来检查包含结果。 我收集了两个包含employeeIds 的文档:Rabin 和Begin 我想查找员工姓名包含 List("ab", "it") 的文档。相关的mongo查询:


    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/'
        ]
      }
    }

在“slashed”参数周围带有单引号的 mongo 查询不返回任何结果。 任何想法如何在 Scala 中实现所需的查询?

【问题讨论】:

    标签: regex mongodb scala


    【解决方案1】:

    你可以这样做:

    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)))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-24
      • 1970-01-01
      • 2020-02-26
      • 1970-01-01
      • 2010-10-04
      • 2019-04-11
      • 2014-08-09
      相关资源
      最近更新 更多