talk about reactivemongo at msug may

Post on 15-Jan-2015

272 Views

Category:

Software

2 Downloads

Preview:

Click to see full reader

DESCRIPTION

My talk about ReactiveMongo driver at Moscow Scala user group May meetup

TRANSCRIPT

Reactive MongoAsynchronous driver for MongoDB

About me

• My name is Andrey Neverov • “General rhetoric” • scala since 2011 • now: scala, akka, spray, mongodb • contribute to reactive mongo

Plan

1. What is reactive mongo 2. Connecting 3. Queries 4. Working with data 5. Streaming 6. Reactive Mongo + Play

Reactive Mongo

• Asynchronous driver • Non-blocking I/O • Scalability • Streaming • GridFS

val driver = new MongoDriverval connection = driver. connection(List(“localhost"))val db = connection.db("db_name")val collection = db.collection(“coll_name")

Connecting

Queries

val query = BSONDocument( “age” -> BSONDocument( “$gt” -> 5 ))

Queries

val animalsOlderThanFive = collection. find(query). cursor[BSONDocument]. collect[List]()!

// Future[List[BSONDocument]]

Queries

animalsOlderThanFive.map { case animals: List[Animal] => …} recover { case t: Throwable => // fail!}

Readerscase class Animal(_id: BSONObjectID, age: Int)object Animal { implicit val reader = new BSONDocumentReader[Animal] { def read(doc: BSONDocument) = { Animal(…) }}}

Readers

object Animal { import reactivemongo.bson.Macros!

val handler = Macros.handler[Animal]}

Readers

val animalsFuture = collection. find(query). cursor[Animal]. collect[List]()!

Streaming

// Enumerator[BSONDocument]val enumeratorOfAnimals = collection. find(query). cursor[BSONDocument]. enumerate()

Streaming

// Iteratee[BSONDocument, Unit]val process: = Iteratee.foreach { a => val name = a[String]("name") val pretty = BSONDocument.pretty(a) println(s"got $name of: $pretty") }

Streaming

enumeratorOfAnimals.apply(process)!

or:!

enumeratorOfAnimals |>>> process

Play

• Play json <-> Reactive mongo bson

• Async actions

• Iteratees

• GridFS

Play

object Application extends Controller with MongoController {!

def collection: JSONCollection = db.collection(“animals")}

Playobject JsonFormats { import play.api.libs.json.Json import play.api.data._ import play.api.data.Forms._!

implicit val format = Json.format[Animal]}

Playdef findByName(name: String) = Action.async { collection. find(Json.obj("name" -> name)) cursor[JsObject]. collect[List]() map { case animals => Ok(Json.arr(animals)) }}

Play

def fromJson = Action.async(parse.json) { r => r.body.validate[Animal].map { a => collection.insert(a).map { … } }.getOrElse { Future(BadRequest(“bad json")) }}

Playdef upload =Action(gridFSBodyParser(gfs)) { r => // Future[ReadFile[BSONValue]] val futureFile = r.body.files.head.ref futureFile.map { file => // do something Ok }}

Thanks!

• http://www.mongodb.org/

• http://reactivemongo.org/

• https://github.com/ReactiveMongo/ReactiveMongo/

• https://github.com/neverov

top related