I have three objects
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])
I plan to store only the Profile object in Mongo DB, but in the Scala App they should be represented by their types.
I am using Subset for the same and have defined of the following nature
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 _)
}
How can I query to and from Mongo Now? Any examples around this?
Integration test is a good example on how to work with nested object, query, update etc. Parts of this test are scattered across the documentation as well.
If you plan to read from Mongo, you need readers for all the parts of your model. If you plan to query or update, you need writers as well. Scala compiler should issue an error if it cannot find a necessary implicit.
How would you query Profile
s:
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)
}
}
I've made a couple of assumptions in this snippet:
Threshold
's fields are defined in object Threshold
(t
is where you get it)Threshold.metric
field is a subset itself, e.g. val metric = "metric".subset(Metric).of[Metric]
, so that you can query metric.where{_.name == metric}
Note that as of version 0.7.0 there is still no reader/writer for Map[String,T]
(though I plan to have it eventually) -- you'll have to develop it (if you need this field) or work around this problem in Metric
's reader/writer.