PageRenderTime 261ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 0ms

/src/main/scala/wtf/scala/lectures/e14/CasbahExamples.scala

https://bitbucket.org/brainoutsource/scala-school-2017-1
Scala | 64 lines | 43 code | 21 blank | 0 comment | 0 complexity | d72826cdf3fb675d9a839eb09c03fbc8 MD5 | raw file
  1. package wtf.scala.lectures.e14
  2. import com.mongodb.casbah.Imports._
  3. import com.mongodb.{BasicDBList, DBObject}
  4. import scala.collection.JavaConverters._
  5. case class Entity(_id: String, params: Param)
  6. case class Param(x: Int, y: Seq[Int])
  7. object CasbahExamples extends App {
  8. val host = "localhost:27017"
  9. val db = "big_cash"
  10. val collection = "test"
  11. val mongoClient: MongoClient = MongoClient(host)
  12. val dbCLient: MongoDB = MongoClient(host)(db)
  13. val collectionClient: MongoCollection = MongoClient(host)(db)(collection)
  14. collectionClient.findOneByID("333").map { o =>
  15. val id = o.get("_id").toString
  16. val params = o.get("params").asInstanceOf[DBObject]
  17. val x = params.as[Double]("x").toInt
  18. val y = params.get("y").asInstanceOf[BasicDBList].iterator().asScala.toList.map(_.toString.toDouble.toInt)
  19. Entity(id, Param(x, y))
  20. }
  21. val cursor = collectionClient.find(MongoDBObject("params.x" -> 15))
  22. val ids = cursor.map { o =>
  23. o.get("_id").toString
  24. }.toList
  25. cursor.close()
  26. val rangeCursor = collectionClient.find("params.x" $gt 14 $lt 16)
  27. val rangeIds = rangeCursor.map { o =>
  28. o.get("_id").toString
  29. }.toList
  30. rangeCursor.close()
  31. val writeResult: WriteResult = collectionClient.insert(MongoDBObject("_id" -> "0011", "params" -> MongoDBObject("x" -> 1, "y" -> List(0, 0, 1))))
  32. writeResult.getN
  33. writeResult.isUpdateOfExisting
  34. writeResult.getUpsertedId
  35. val removedDoc: Option[DBObject] = collectionClient.findAndRemove(MongoDBObject("_id" -> "001"))
  36. print(removedDoc)
  37. val removeResult: WriteResult = collectionClient.remove(MongoDBObject("_id" -> "0011", "params" -> MongoDBObject("x" -> 1, "y" -> List(0, 0, 1))))
  38. val updateResult: WriteResult = collectionClient.update(MongoDBObject("_id" -> "0011"),
  39. $set("params.x" -> 1),
  40. upsert = false,
  41. multi = true)
  42. val saveResult: WriteResult = collectionClient.save(MongoDBObject("_id" -> "9", "params" -> MongoDBObject("x" -> 1, "y" -> List(0, 0, 1))))
  43. }