首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Scala casbah DSL查询

Scala casbah DSL查询
EN

Stack Overflow用户
提问于 2013-09-18 01:42:56
回答 1查看 732关注 0票数 0

我正在学习斯卡拉,也在尝试蒙戈。我正在创建一个函数,它接收一个Map[String, Any]作为参数,我想为它返回适当的MongoDBObject

代码语言:javascript
复制
def parse(query: Map[String, Any]): MongoDBObject = {
  val result = query("operation") match {
    case "all" => query("field").toString $all query("value").asInstanceOf[List[String]]
    case "in" => query("field").toString $in query("value").asInstanceOf[List[String]]
    case "regex" => query("field").toString $regex query("value")
    case "eq" => query("field").toString $eq query("value")
    case "gt" => query("field").toString $gt query("value")
    case "gte" => query("field").toString $gte query("value")
    case "lt" => query("field").toString $lt query("value")
    case "lte" => query("field").toString $lte query("value")
    case "exists" => query("field").toString $exists query("value").asInstanceOf[Boolean]
    case "size" => query("field").toString $size query("value").asInstanceOf[Int]
    case "where" => $where(query("value").toString)
    case _ => throw new NotImplementedError("Unknown operation")
  }
}

我有些问题。

  • 编译器说$regex不是String的成员。我也不知道原因。
  • 编译器说Any不是有效的查询参数。我想我应该转换为int、string、date或任何其他有效的Mongo类型。有什么方法可以在没有反射的情况下解决这个问题来解决值是什么类型?
  • 对于$mod操作,我应该给出两个数值作为参数。我是否应该使用List作为映射的值,并获得第一项和第二项?
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-09-18 02:18:09

它抱怨$regex,因为它没有在右边找到一个可regex的对象来应用用于解析$regex方法的转换--这也是您在以下所有调用中都会遇到的问题。

对于Any (以及$mod)的问题,我可以提出一种不同的方法吗?您没有Any的类型信息,因此无法真正绕过运行时转换(我也不知道反射如何帮助您。)这样你就不会得到静态类型系统的任何好处了。下面是一种实现方法的草图,您可以使用类型层次结构来实现这样的方法来执行类型安全:

代码语言:javascript
复制
sealed trait Query

case class All(field: String, value: List[String]) extends Query 
...
case class GreaterThan(field: String, value: Int) extends Query 
...
case class Mod(field: String, divisor: Int, remainder: Int) extends Query

def parse(q: Query): MongoDBObject = {
   q match {
      case All(f, v) => f $all v
      ...
      case GreaterThan(f, v) => f $gt v
      ...
      case Mod(f, d, r) => f $mod (d, r)
   }
}

或者,您可以在Query上定义一个抽象执行方法,并在每个扩展类中重写它,而不是在parse中执行match语句。在那里,您可以使用类型参数或泛型类型进一步抽象,例如允许GreaterThan接受任何Numeric类型。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18862587

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档