0

我有三个对象

case class Metric(val name: String, val tags: Map[String, String]) 

case class Threshold(val metric: Metric, val critical: Long, val warning: Long)

class Profile(val name: String, val thresholds: List[Threshold])

我打算只将 Profile 对象存储在 Mongo DB 中,但在 Scala 应用程序中,它们应该由它们的类型表示。

我正在使用相同的子集,并定义了以下性质

implicit val reader = ValueReader[Threshold]({
case metric(metric) ~ critical(critical) ~ warning(warning) =>
  new Threshold(metric, critical, warning)
})
implicit val writer = {
def f(threshold: Threshold): DBObject =
  (metric -> threshold.metric) ~ (critical -> threshold.critical) ~ (warning -> threshold.warning)
ValueWriter(f _)
} 

我如何查询往返 Mongo Now?有这方面的例子吗?

4

1 回答 1

1

集成测试是关于如何使用嵌套对象、查询、更新等的一个很好的例子。这个测试的部分内容也分散在文档中。

如果您打算从 Mongo 阅读,则需要阅读器来阅读模型的所有部分。如果你打算查询或更新,你也需要作家。如果 Scala 编译器找不到必要的隐式,它应该发出错误。

您将如何查询Profiles:

object Profile {
  val name = "name".fieldOf[String]
  val thresholds = "thresholds".subset(Threshold).of[List[Threshold]]

  // typical query:
  def alarmsFor(metric: String) =
    collection.find( thresholds elemMatch {t =>
      t.metric.where{_.name == metric} && t.critical > 10
    } ) map {
      case name(n) ~ thresholds(t) => new Profile(n, t)
    }
}

我在这个片段中做了几个假设:

  • Threshold的字段定义在object Thresholdt是你得到它的地方)
  • Threshold.metric字段本身就是一个子集,例如val metric = "metric".subset(Metric).of[Metric],以便您可以查询metric.where{_.name == metric}

请注意,从 0.7.0 版开始,仍然没有读取器/写入器Map[String,T](尽管我计划最终拥有它)——您必须开发它(如果您需要此字段)或在Metric's reader中解决此问题/作家。

于 2012-02-01T11:30:53.263 回答