Share
Embed
Transcript
69 slides
-
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) -
• Core Java driver • Python driver • JRuby driver
• Scala driver • Clojure community driver - Monger • Higher Level Frameworks - ODMs Java and the JVM -
Connecting com.mongodb.MongoClient mongoClient = new MongoClient(); com.mongodb.DB db = mongoClient.getDB(
"bookstore" ); com.mongodb.DBCollection coll = db.getCollection( "books" ); -
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 ) ); -
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 ) ); -
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 ); -
Querying com.mongodb.DBObject query = new BasicDBObject(); query.put( "tag", "java" );
query.put( "price", new BasicDBObject( "$lt", 40.00 ) ); -
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... } -
Query Builder DBObject query = QueryBuilder.start( "price" ) .lessThan( 40.00
) .and( "tag" ) .is( "java" ) .get(); -
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 ) ); -
• 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 -
• 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 -
• Wraps the Java driver • Provide idiomatic Scala interface
to MongoDB • Improved query dsl and interfaces Scala -
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 ) } -
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 ... -
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"} -
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"} -
Scala val mongo: MongoClient = MongoClient()("bookstore")("books") def findAll() = for
( book <- mongo.find() ) yield new Book(book) findAll().foreach(b => println("<Book> " + b)) -
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) ... -
• 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 -
• ReplicaSet support • Authentication support • GridFS support (streaming
capable) • Cursors (providing a stream of documents) • Bulk inserts • Database commands support • Indexing operations ReactiveMongo -
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)) }) -
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) } -
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")) -
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) -
Morphia @Entity("books") // MongoDB collection to use class Book {
public Book () { } // ... } -
Morphia @Entity("books") class Book { @Id private ObjectId id; public
Book () { } // ... } -
Morphia @Entity("books") class Book { @Id private ObjectId id; private
List<String> tags = new ArrayList<String>(); public Book () { } // ... } -
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 { // ... } -
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 { // ... } -
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 () { } // ... } -
Morphia - Inserting Datastore ds = new Morphia().createDatastore("shop") Book book
= new Book() // set fields on the book // ... ds.insert(book); -
Spring Data Document @Document(collection="books") public class Book { @Id private
String id; private List<String> tags = new ArrayList<String>(); private Price price; // ... } -
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; // ... } -
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; // ... } -
Spring Data - Connecting ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-context.xml"); MongoOperations
ops = ctx.getBean("mongoTemplate", MongoOperations.class); -
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); -
Spring Data - Querying MongoOperations ops = ctx.getBean("mongoTemplate", MongoOperations.class); Book
book = ops.findOne(query(where("price").lt(40)), Book.class); -
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); -
Spring Data - Querying public interface BookRepository extends CrudRepository<Book, String>
{ public Book findByAuthor(String author); } -
Spring Data - Querying ApplicationContext ctx = new ClassPathXmlApplicationContext( "spring-context.xml");
BookRepository repo = ctx.getBean("bookRepository", BookRepository.class); -
Spring Data - Querying ApplicationContext ctx = new ClassPathXmlApplicationContext( "spring-context.xml");
BookRepository repo = ctx.getBean("bookRepository", BookRepository.class); Book book = repo.findByAuthor("Eric"); -
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> -
• 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 -
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]