Slide 1

Slide 1 text

MongoDB and the JVM Ross Lawley Software Engineer, 10gen @RossC0

Slide 2

Slide 2 text

Working with MongoDB

Slide 3

Slide 3 text

Official 10Gen Drivers

Slide 4

Slide 4 text

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)

Slide 5

Slide 5 text

• Core Java driver • Python driver • JRuby driver • Scala driver • Clojure community driver - Monger • Higher Level Frameworks - ODMs Java and the JVM

Slide 6

Slide 6 text

Using the Java Driver

Slide 7

Slide 7 text

Connecting

Slide 8

Slide 8 text

Connecting com.mongodb.MongoClient mongoClient = new MongoClient(serverName, port);

Slide 9

Slide 9 text

Connecting com.mongodb.MongoClient mongoClient = new MongoClient(); com.mongodb.DB db = mongoClient.getDB( "bookstore" );

Slide 10

Slide 10 text

Connecting com.mongodb.MongoClient mongoClient = new MongoClient(); com.mongodb.DB db = mongoClient.getDB( "bookstore" ); com.mongodb.DBCollection coll = db.getCollection( "books" );

Slide 11

Slide 11 text

Inserting

Slide 12

Slide 12 text

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 ) );

Slide 13

Slide 13 text

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 ) );

Slide 14

Slide 14 text

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 );

Slide 15

Slide 15 text

Querying

Slide 16

Slide 16 text

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

Slide 17

Slide 17 text

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... }

Slide 18

Slide 18 text

Query Builder DBObject query = QueryBuilder.start( "price" ) .lessThan( 40.00 ) .and( "tag" ) .is( "java" ) .get();

Slide 19

Slide 19 text

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 ) );

Slide 20

Slide 20 text

The future of the java driver

Slide 21

Slide 21 text

Other JVM Languages

Slide 22

Slide 22 text

Official 10Gen Drivers - on the JVM

Slide 23

Slide 23 text

• 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

Slide 24

Slide 24 text

• 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

Slide 25

Slide 25 text

• Wraps the Java driver • Provide idiomatic Scala interface to MongoDB • Improved query dsl and interfaces Scala

Slide 26

Slide 26 text

Scala

Slide 27

Slide 27 text

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 ) }

Slide 28

Slide 28 text

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 ...

Slide 29

Slide 29 text

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"}

Slide 30

Slide 30 text

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"}

Slide 31

Slide 31 text

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

Slide 32

Slide 32 text

Scala val mongo: MongoClient = MongoClient()("bookstore")("books") def findAll() = for ( book <- mongo.find() ) yield new Book(book) findAll().foreach(b => println(" " + b)) val query: DBObject = ("price" $lt 40.00) ++ ("tag" -> "scala") mongo.find(query) ...

Slide 33

Slide 33 text

Community drivers

Slide 34

Slide 34 text

Scala

Slide 35

Slide 35 text

• 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

Slide 36

Slide 36 text

• ReplicaSet support • Authentication support • GridFS support (streaming capable) • Cursors (providing a stream of documents) • Bulk inserts • Database commands support • Indexing operations ReactiveMongo

Slide 37

Slide 37 text

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)) })

Slide 38

Slide 38 text

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) }

Slide 39

Slide 39 text

Clojure

Slide 40

Slide 40 text

http://clojuremongodb.info/ Monger

Slide 41

Slide 41 text

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"))

Slide 42

Slide 42 text

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)

Slide 43

Slide 43 text

Higher Level Abstractions

Slide 44

Slide 44 text

Morphia (Java)

Slide 45

Slide 45 text

Morphia @Entity("books") // MongoDB collection to use class Book { public Book () { } // ... }

Slide 46

Slide 46 text

Morphia @Entity("books") class Book { @Id private ObjectId id; public Book () { } // ... }

Slide 47

Slide 47 text

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

Slide 48

Slide 48 text

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

Slide 49

Slide 49 text

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

Slide 50

Slide 50 text

Morphia @Entity("books") class Book { @Id private ObjectId id; private List tags = new ArrayList(); @Embedded private Price price; @Reference private Author author; @Property("publicationYear") private int year; public Book () { } // ... }

Slide 51

Slide 51 text

Morphia - Inserting Datastore ds = new Morphia().createDatastore("shop") Book book = new Book() // set fields on the book // ... ds.insert(book);

Slide 52

Slide 52 text

Spring Data

Slide 53

Slide 53 text

Spring Data Document @Document(collection="books") public class Book { // ... }

Slide 54

Slide 54 text

Spring Data Document @Document(collection="books") public class Book { @Id private String id; // ... }

Slide 55

Slide 55 text

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

Slide 56

Slide 56 text

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

Slide 57

Slide 57 text

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

Slide 58

Slide 58 text

Spring Data - Connecting ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-context.xml"); MongoOperations ops = ctx.getBean("mongoTemplate", MongoOperations.class);

Slide 59

Slide 59 text

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);

Slide 60

Slide 60 text

Spring Data - Querying MongoOperations ops = ctx.getBean("mongoTemplate", MongoOperations.class); Book book = ops.findOne(query(where("price").lt(40)), Book.class);

Slide 61

Slide 61 text

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);

Slide 62

Slide 62 text

Spring Data - Querying public interface BookRepository extends CrudRepository { public Book findByAuthor(String author); }

Slide 63

Slide 63 text

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

Slide 64

Slide 64 text

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

Slide 65

Slide 65 text

Spring Data Configuration

Slide 66

Slide 66 text

• 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

Slide 67

Slide 67 text

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]

Slide 68

Slide 68 text

• http://www.mongodb.org/display/DOCS/Drivers • http://reactivemongo.org/ • http://clojuremongodb.info/ • http://code.google.com/p/morphia/ • http://www.springsource.org/spring-data/mongodb/ More Information

Slide 69

Slide 69 text

Thanks! Ross Lawley Software Engineer, 10gen @RossC0