PageRenderTime 98ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/src/main/scala/CasbahQuerying.scala

http://github.com/bwmcadams/mongoScalaWebinar
Scala | 54 lines | 26 code | 18 blank | 10 comment | 4 complexity | 642b6d067f05f0cae72cbd4e9d3a7f3d MD5 | raw file
  1. package com.mongodb.demo;
  2. package webinar;
  3. package scala;
  4. // Imports Commons, Core, and the Query DSL
  5. import com.mongodb.casbah.Imports._
  6. // Tools to let us use Joda instead of JDK Dates,
  7. import com.mongodb.casbah.commons.conversions.scala._
  8. import org.scala_tools.time.Imports._
  9. object CasbahQuerying extends Application {
  10. import CasbahDemo._
  11. // What about querying? Lets find all the non-US events
  12. for (x <- mongo.find(MongoDBObject("location.country" ->
  13. MongoDBObject("$ne" -> "USA")))) println(x)
  14. /* There's a problem here: We got back the Webinars too because
  15. They don't have a country at all, so they aren't "USA"
  16. */
  17. println("\n\nTesting for existence of Location.Country:")
  18. for (x <- mongo.find(MongoDBObject("location.country" -> MongoDBObject(
  19. "$ne" -> "USA",
  20. "$exists" -> true
  21. )))) println(x)
  22. // This is getting a bit unwieldy. Thankfully, Casbah offers a DSL
  23. val q = $or ("location.country" -> "USA", "location.country" -> "Japan")
  24. println("\n Created a DBObject: %s".format(q))
  25. println("\n Querying using DSL Object...")
  26. for (x <- mongo.find(q)) println(x)
  27. // It's possible to construct more complex queries too.
  28. // Lets find everything in February
  29. println("\n February Events...")
  30. val start = new DateTime(2011, 2, 1, 0, 0, 0, 0)
  31. val end = new DateTime(2011, 3, 1, 0, 0, 0, 0)
  32. val dateQ = "date.start" $gte start $lt end
  33. println("\n Date Query: %s".format(dateQ))
  34. for (x <- mongo.find(dateQ, MongoDBObject("name" -> true, "date" -> true))) println(x)
  35. }
  36. // vim: set ts=2 sw=2 sts=2 et: