Upgrade to Pro — share decks privately, control downloads, hide ads and more …

MongoDB and the JVM

rozza
January 15, 2013

MongoDB and the JVM

rozza

January 15, 2013
Tweet

More Decks by rozza

Other Decks in Technology

Transcript

  1. MongoDB drivers • Official Support for 13 languages • Community

    drivers for tons more – Clojure, R, lua etc. • Drivers connect to mongo servers • Drivers translate BSON into native types • mongo shell is not a driver, but works like one in some ways • Installed using typical means (npm, pecl, gem, pip)
  2. • Core Java driver • Python driver • JRuby driver

    • Scala driver • Clojure community driver - Monger • Higher Level Frameworks - ODMs Java and the JVM
  3. Connecting com.mongodb.MongoClient mongoClient = new MongoClient(); com.mongodb.DB db = mongoClient.getDB(

    "bookstore" ); com.mongodb.DBCollection coll = db.getCollection( "books" );
  4. Inserting com.mongodb.DBCollection coll = db.getCollection( "books" ); ... com.mongodb.DBObject newBook

    = new BasicDBObject(); newBook.put( "title", "Java Concurrency in Practice" ); newBook.put( "author", "Brian Goetz" ); newBook.put( "price", new BasicDBObject( "msrp", 38.99 ) );
  5. Inserting com.mongodb.DBCollection coll = db.getCollection( "books" ); ... com.mongodb.DBObject newBook

    = new BasicDBObject(); newBook.put( "title", "Java Concurrency in Practice" ); newBook.put( "author", "Brian Goetz" ); newBook.put( "price", new BasicDBObject( "msrp", 38.99 ) );
  6. Inserting com.mongodb.DBCollection coll = db.getCollection( "books" ); ... com.mongodb.DBObject newBook

    = new BasicDBObject(); newBook.put( "title", "Java Concurrency in Practice" ); newBook.put( "author", "Brian Goetz" ); newBook.put( "price", new BasicDBObject( "msrp", 38.99 ) ); coll.insert( newBook );
  7. Querying com.mongodb.DBObject query = new BasicDBObject(); query.put( "tag", "java" );

    query.put( "price", new BasicDBObject( "$lt", 40.00 ) );
  8. Querying com.mongodb.DBObject query = new BasicDBObject(); query.put( "tag", "java" );

    query.put( "price", new BasicDBObject( "$lt", 40.00 ) ); for ( DBObject doc : coll.find( query ) ) { // ...for every document found, do something... }
  9. Query Builder DBObject query = QueryBuilder.start( "price" ) .lessThan( 40.00

    ) .and( "tag" ) .is( "java" ) .get(); ... DBObject query = new BasicDBObject(); query.put( "tag", "java" ); query.put( "price", new BasicDBObject( "$lt", 40.00 ) );
  10. • Allows Python's clear syntax on the JVM • PyMongo

    uses native python code and has no hooks into the Java driver • Some care needed to ensure cursors are closed due to different garbage collection models. Jython
  11. • Support for JRuby 1.6.x and 1.7.x • Native Java

    extensions are bundled in with the BSON gem. • Utilises the Java driver for improved BSON decoding and performance. JRuby
  12. • Wraps the Java driver • Provide idiomatic Scala interface

    to MongoDB • Improved query dsl and interfaces Scala
  13. Scala case class Book(id: ObjectId, author: String, isbn: String, price:

    Price, year: Int, tags: Seq[String], title: String, publisher: String, edition: Option[String]) { def toDBObject = MongoDBObject( "author" -> author, "_id" -> id, "isbn" -> isbn, "price" -> price.toDBObject, "publicationYear" -> year, "tags" -> tags, "title" -> title, "publisher" -> publisher, "edition" -> edition ) }
  14. Scala // Connect to default - localhost, 27017 scala> val

    mongoClient = MongoClient() mongoClient: com.mongodb.casbah.MongoClient ... // Chainable api scala> val mongoColl = mongoClient("bookstore")("books") mongoColl: com.mongodb.casbah.MongoCollection ...
  15. Scala scala> val builder = MongoDBObject.newBuilder scala> builder += "foo"

    -> "bar" scala> builder += "x" -> "y" scala> builder += ("pie" -> 3.14) scala> builder += ("spam" -> "eggs", "mmm" -> "bacon") builder.type = com.mongodb.casbah.commons.MongoDBObjectBuilder // Return a DBObject scala> val newObj = builder.result newObj: com.mongodb.casbah.commons.Imports.DBObject = { "foo" : "bar" , "x" : "y" , "pie" : 3.14 , "spam" : "eggs" , "mmm" : "bacon"}
  16. Scala scala> val newObj = MongoDBObject("foo" -> "bar", | "x"

    -> "y", | "pie" -> 3.14, | "spam" -> "eggs") newObj: com.mongodb.casbah.commons.Imports.DBObject = { "foo" : "bar" , "x" : "y" , "pie" : 3.14 , "spam" : "eggs"}
  17. Scala val mongo: MongoClient = MongoClient()("bookstore")("books") def findAll() = for

    ( book <- mongo.find() ) yield new Book(book) findAll().foreach(b => println("<Book> " + b))
  18. Scala val mongo: MongoClient = MongoClient()("bookstore")("books") def findAll() = for

    ( book <- mongo.find() ) yield new Book(book) findAll().foreach(b => println("<Book> " + b)) val query: DBObject = ("price" $lt 40.00) ++ ("tag" -> "scala") mongo.find(query) ...
  19. • ReactiveMongo - asynchronous / non blocking by the guys

    at zenexity! hattip Stephane Godbillon! • Hammersmith - Netty + Akka.IO interfaces, strongly functional and callback based Scala - community drivers
  20. • ReplicaSet support • Authentication support • GridFS support (streaming

    capable) • Cursors (providing a stream of documents) • Bulk inserts • Database commands support • Indexing operations ReactiveMongo
  21. ReactiveMongo // select only my documents val query = BSONDocument("firstName"

    -> BSONString("Ross")) // get a Cursor[BSONDocument] val cursor = collection.find(query) //Enumerate this cursor and print a readable version cursor.enumerate.apply(Iteratee.foreach { doc => println("found document: " + DefaultBSONIterator.pretty(doc.bsonIterator)) })
  22. ReactiveMongo // select only my documents val query = BSONDocument("firstName"

    -> BSONString("Ross")) // get a Cursor[BSONDocument] val cursor = collection.find(query) // Create a list using the toList helper val futurelist = cursor.toList futurelist.onSuccess { case list => val names = list.map( _.getAs[BSONString]("lastName").get.value) println("got names: " + names) }
  23. Monger (ns my.service.server (:require [monger.core :as mg])) ;; localhost, default

    port (mg/connect!) ;; set default database using set-db (mg/set-db! (mg/get-db "monger-test"))
  24. Monger (connect!) (set-db! (monger.core/get-db "monger-test")) ;; with explicit document id

    (recommended) (insert "documents" { :_id (ObjectId.) :first_name "John" :last_name "Lennon" }) ;; with a different write concern (insert "documents" { :_id (ObjectId.) :first_name "John" :last_name "Lennon" } WriteConcern/JOURNAL_SAFE)
  25. Morphia @Entity("books") class Book { @Id private ObjectId id; private

    List<String> tags = new ArrayList<String>(); public Book () { } // ... }
  26. Morphia @Entity("books") class Book { @Id private ObjectId id; private

    List<String> tags = new ArrayList<String>(); @Embedded private Price price; public Book () { } // ... } @Embedded class Price { // ... }
  27. Morphia @Entity("books") class Book { @Id private ObjectId id; private

    List<String> tags = new ArrayList<String>(); @Embedded private Price price; @Reference private Author author; public Book () { } // ... } @Entity("authors") class Author { // ... }
  28. Morphia @Entity("books") class Book { @Id private ObjectId id; private

    List<String> tags = new ArrayList<String>(); @Embedded private Price price; @Reference private Author author; @Property("publicationYear") private int year; public Book () { } // ... }
  29. Morphia - Inserting Datastore ds = new Morphia().createDatastore("shop") Book book

    = new Book() // set fields on the book // ... ds.insert(book);
  30. Spring Data Document @Document(collection="books") public class Book { @Id private

    String id; private List<String> tags = new ArrayList<String>(); private Price price; // ... }
  31. Spring Data Document @Document(collection="books") public class Book { @Id private

    String id; private List<String> tags = new ArrayList<String>(); private Price price; @DBRef private Author author; // ... }
  32. Spring Data Document @Document(collection="books") public class Book { @Id private

    String id; private List<String> tags = new ArrayList<String>(); private Price price; @DBRef private Author author; @Field("publicationYear") private int year; // ... }
  33. Spring Data - Inserting ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-context.xml"); MongoOperations

    ops = ctx.getBean("mongoTemplate", MongoOperations.class); Book book = new Book(); // set fields on the book // ... ops.insert(book);
  34. Spring Data - Querying MongoOperations ops = ctx.getBean("mongoTemplate", MongoOperations.class); Book

    book = ops.findOne(query(where("price").lt(40)), Book.class); book = ops.findById(book.getId(), Book.class);
  35. Spring Data - Querying ApplicationContext ctx = new ClassPathXmlApplicationContext( "spring-context.xml");

    BookRepository repo = ctx.getBean("bookRepository", BookRepository.class);
  36. Spring Data - Querying ApplicationContext ctx = new ClassPathXmlApplicationContext( "spring-context.xml");

    BookRepository repo = ctx.getBean("bookRepository", BookRepository.class); Book book = repo.findByAuthor("Eric");
  37. Spring Data Configuration <?xml version="1.0" encoding="UTF-8"?> <beans ... xmlns:mongo="http://www.springframework.org/schema/data/mongo" xsi:schemaLocation="

    ... http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd"> <mongo:mongo id="mongo" > <mongo:options auto-connect-retry="true" /> </mongo:mongo> <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"> <constructor-arg ref="mongo" /> <constructor-arg value="news" /> </bean> <mongo:repositories base-package="org.mongodb.news.repositories"/> </beans>
  38. • If you're coding on the JVM you have many

    options for interacting with MongoDB • Multiple native drivers • Some great community drivers • Frameworks to simplify development In Summary
  39. Click to edit Master text styles More Information Resource Location

    MongoDB Downloads www.mongodb.org/downloads Free Online Training education.10gen.com Webinars and Events www.10gen.com/events White Papers www.10gen.com/white-papers Customer Case Studies www.10gen.com/customers Presentations www.10gen.com/presentations Documentation docs.mongodb.org Additional Info [email protected]