SlideShare a Scribd company logo
1 of 25
Download to read offline
Java Development with
      MongoDB
       James Williams
 Software Engineer, BT/Ribbit
Agenda

 Java Driver basics
    Making Connections
    Managing Collections
    BasicDBObjectBuilder
    Document Queries
    GridFS
 Morphia
 Beyond the Java language
    Groovy utilities
    Grails plugin
Making a Connection

import com.mongodb.Mongo;
import com.mongodb.DB;

Mongo m = new Mongo();
Mongo m = new Mongo( "localhost" );
Mongo m = new Mongo( "localhost" , 27017 );

DB db = m.getDB( "mydb" );
Working with Collections

    Getting all collections in the database
Set<String> colls = db.getCollectionNames();
for (String s : colls) {
  System.out.println(s);
}
    Getting a single collection
DBCollection coll = db.getCollection("testCollection")
Inserting Documents

BasicDBObject doc = new BasicDBObject();
 doc.put("name", "MongoDB");
doc.put("type", "database");
doc.put("count", 1);

BasicDBObject info = new BasicDBObject();
info.put("x", 203);
info.put("y", 102);
doc.put("info", info);
coll.insert(doc);
BasicDBObjectBuilder

    Utility for building objects
    Can coerce Maps (and possibly JSON*) to DBObjects
    Example:
BasicDBObjectBuilder.start()
  .add( "name" , "eliot" )
  .add( "number" , 17 )
  .get();
Document Queries

DBObject myDoc = coll.findOne();
// can also use
BasicDBObject query = new BasicDBObject(); query.put("i", 71);
DBCursor cur = coll.find(query);
GridFS

 mechanism for storing files larger than 4MB
 files are chunked allowing fetching of a portion or out of
 order
 chunking is mostly transparent to underlying operating
 system
 can store files in buckets, a MongoDB metaphor for folders
 default is the fs bucket
Saving a file to GridFS

def mongo = new Mongo(host)
def gridfs = new GridFS(mongo.getDB("db"))

def save(inputStream, contentType, filename) {
  def inputFile = gridfs.createFile(inputStream)
  inputFile.setContentType(contentType)
  inputFile.setFilename(filename)
  inputFile.save()
}
Retrieving/Deleting a file

def retrieveFile(String filename) {
  return gridfs.findOne(filename)
}

def deleteFile(String filename) {
  gridfs.remove(filename)
}
Morphia

 Apache 2 Licensed
 brings Hibernate/JPA paradigms to MongoDB
 allows annotating of POJOs to make converting them
 between MongoDB and Java very easy
 supports DAO abstractions
 offers type-safe query support
 compatible with GWT, Guice, Spring, and DI frameworks
Morphia Annotations

 @Id
 @Entity
 @Embedded
 @Reference
 @Indexed
 @Serialized
 @Property
Creating a Morphia POJO

import com.google.code.morphia.annotations.*;

@Entity("collectionName")
public class Contact {
  @Id
  private String id; //generated by MongoDB

    private String firstName;
    private String lastName;
    @Embedded
    private List<PhoneNumber> phoneNumbers;

    // getters and setters
}
Mapping a POJO to a Mongo doc

Morphia morphia = ...;
Mongo mongo = ...;
DB db = mongo.getDB("contacts");

Contact contact = ...;

// map the contact to a DBObject
DBObject contactObj = morphia.toDBObject(contact);

db.getCollection("personal").save(contactObj);
Getting a POJO from a Mongo doc

Morphia morphia = ...;
Mongo mongo = ...;
DB db = mongo.getDB("contacts");

String contactId = ...;

//load the object from the collection
BasicDBObject idObj = new BasicDBObject(
   "_id", new ObjectId(contactId)
);
BasicDBObject obj = (BasicDBObject)
  db.getCollection("personal").findOne(idObj);
Contact contact = morphia.fromDBObject(Contact.class, obj);
DAOs

 Encapsulate saving and retrieving objects
 Auto-converts to and from POJOs
 Can provide constraints on searches
 Key functions:
    get(<mongoId>)
    find() or find(constraints)
    findOne(constraints)
    deleteById(<mongoId>)
DAO Example

import com.mongodb.Mongo
import com.google.code.morphia.*

class EntryDAO extends DAO<BlogEntry,String> {
   public EntryDAO(Morphia morphia, Mongo mongo) {
super(mongo, morphia, "entries")
   }
}
Constraints Examples

dao.find(new Constraints()                                    .
orderByDesc("dateCreated")
).asList()

dao.find(
new Constraints()
.field("dateCreated").greaterThanOrEqualTo(date).field("title").
equalTo(params.title)
).asList()
Beyond the Java Language
MongoDB with Groovy

 Metaprogramming with MongoDB can reduce LOC
 Dynamic finders
 Fluent interface mirroring Ruby and Python
Groovy + MongoDB

Java
BasicDBObject doc = new BasicDBObject();
doc.put("name", "MongoDB");
doc.put("type", "database");
doc.put("count", 1);
coll.insert(doc);

Groovier
def doc = [name:"MongoDB",type:"database", count:1, info:
  [x:203, y:102] ] as BasicDBObject
coll.insert(doc)

Grooviest (using groovy-mongo)
coll.insert([name:"MongoDB", type:"database", info: [x:203, y:102]])
Dynamic Finders

    can build complex queries at runtime
    can even reach into objects for addition query parameters

Ex. collection.findByAuthorAndPostCreatedGreaterThan(...)
  collection.findByComments_CreatedOn(...)
How dynamic finders work

 Groovy receives the request for the method
 The method is not found (invoking methodMissing)
 The method name used to construct a query template
 The method is cached
 The method is invoked with the parameters
 Future invocations use the cached method
MongoDB Grails Plugin

 Replaces JDBC layer in Grails applications
 Can use dynamic finders
 Requires only slight modifications to domain classes
 http://github.com/mpriatel/mongodb-grails
Links

  Personal Blog: http://jameswilliams.be/blog
  Twitter: http://twitter.com/ecspike

  Morphia: http://code.google.com/p/morphia
  Utilities for Groovy: http://github.com/jwill/groovy-mongo
  MongoDB Grails plugin: http://github.
  com/mpriatel/mongodb-grails

More Related Content

What's hot

MongoDB: Easy Java Persistence with Morphia
MongoDB: Easy Java Persistence with MorphiaMongoDB: Easy Java Persistence with Morphia
MongoDB: Easy Java Persistence with MorphiaScott Hernandez
 
Spring Data, Jongo & Co.
Spring Data, Jongo & Co.Spring Data, Jongo & Co.
Spring Data, Jongo & Co.Tobias Trelle
 
Webinar: MongoDB Persistence with Java and Morphia
Webinar: MongoDB Persistence with Java and MorphiaWebinar: MongoDB Persistence with Java and Morphia
Webinar: MongoDB Persistence with Java and MorphiaMongoDB
 
Reactive Access to MongoDB from Java 8
Reactive Access to MongoDB from Java 8Reactive Access to MongoDB from Java 8
Reactive Access to MongoDB from Java 8Hermann Hueck
 
Getting Started with MongoDB and NodeJS
Getting Started with MongoDB and NodeJSGetting Started with MongoDB and NodeJS
Getting Started with MongoDB and NodeJSMongoDB
 
Webinar: Building Your First App with MongoDB and Java
Webinar: Building Your First App with MongoDB and JavaWebinar: Building Your First App with MongoDB and Java
Webinar: Building Your First App with MongoDB and JavaMongoDB
 
Real World Application Performance with MongoDB
Real World Application Performance with MongoDBReal World Application Performance with MongoDB
Real World Application Performance with MongoDBMongoDB
 
Back to Basics Webinar 5: Introduction to the Aggregation Framework
Back to Basics Webinar 5: Introduction to the Aggregation FrameworkBack to Basics Webinar 5: Introduction to the Aggregation Framework
Back to Basics Webinar 5: Introduction to the Aggregation FrameworkMongoDB
 
BedCon 2013 - Java Persistenz-Frameworks für MongoDB
BedCon 2013 - Java Persistenz-Frameworks für MongoDBBedCon 2013 - Java Persistenz-Frameworks für MongoDB
BedCon 2013 - Java Persistenz-Frameworks für MongoDBTobias Trelle
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on AndroidSven Haiges
 
NoSQL and JavaScript: a Love Story
NoSQL and JavaScript: a Love StoryNoSQL and JavaScript: a Love Story
NoSQL and JavaScript: a Love StoryAlexandre Morgaut
 
What do you mean, Backwards Compatibility?
What do you mean, Backwards Compatibility?What do you mean, Backwards Compatibility?
What do you mean, Backwards Compatibility?Trisha Gee
 
Map/Confused? A practical approach to Map/Reduce with MongoDB
Map/Confused? A practical approach to Map/Reduce with MongoDBMap/Confused? A practical approach to Map/Reduce with MongoDB
Map/Confused? A practical approach to Map/Reduce with MongoDBUwe Printz
 
DrupalCon Chicago Practical MongoDB and Drupal
DrupalCon Chicago Practical MongoDB and DrupalDrupalCon Chicago Practical MongoDB and Drupal
DrupalCon Chicago Practical MongoDB and DrupalDoug Green
 
Benefits of Using MongoDB Over RDBMS (At An Evening with MongoDB Minneapolis ...
Benefits of Using MongoDB Over RDBMS (At An Evening with MongoDB Minneapolis ...Benefits of Using MongoDB Over RDBMS (At An Evening with MongoDB Minneapolis ...
Benefits of Using MongoDB Over RDBMS (At An Evening with MongoDB Minneapolis ...MongoDB
 
MongoDB World 2016: Deciphering .explain() Output
MongoDB World 2016: Deciphering .explain() OutputMongoDB World 2016: Deciphering .explain() Output
MongoDB World 2016: Deciphering .explain() OutputMongoDB
 

What's hot (19)

MongoDB: Easy Java Persistence with Morphia
MongoDB: Easy Java Persistence with MorphiaMongoDB: Easy Java Persistence with Morphia
MongoDB: Easy Java Persistence with Morphia
 
Spring Data, Jongo & Co.
Spring Data, Jongo & Co.Spring Data, Jongo & Co.
Spring Data, Jongo & Co.
 
Webinar: MongoDB Persistence with Java and Morphia
Webinar: MongoDB Persistence with Java and MorphiaWebinar: MongoDB Persistence with Java and Morphia
Webinar: MongoDB Persistence with Java and Morphia
 
Reactive Access to MongoDB from Java 8
Reactive Access to MongoDB from Java 8Reactive Access to MongoDB from Java 8
Reactive Access to MongoDB from Java 8
 
Getting Started with MongoDB and NodeJS
Getting Started with MongoDB and NodeJSGetting Started with MongoDB and NodeJS
Getting Started with MongoDB and NodeJS
 
Indexing
IndexingIndexing
Indexing
 
Webinar: Building Your First App with MongoDB and Java
Webinar: Building Your First App with MongoDB and JavaWebinar: Building Your First App with MongoDB and Java
Webinar: Building Your First App with MongoDB and Java
 
Real World Application Performance with MongoDB
Real World Application Performance with MongoDBReal World Application Performance with MongoDB
Real World Application Performance with MongoDB
 
Back to Basics Webinar 5: Introduction to the Aggregation Framework
Back to Basics Webinar 5: Introduction to the Aggregation FrameworkBack to Basics Webinar 5: Introduction to the Aggregation Framework
Back to Basics Webinar 5: Introduction to the Aggregation Framework
 
BedCon 2013 - Java Persistenz-Frameworks für MongoDB
BedCon 2013 - Java Persistenz-Frameworks für MongoDBBedCon 2013 - Java Persistenz-Frameworks für MongoDB
BedCon 2013 - Java Persistenz-Frameworks für MongoDB
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on Android
 
NoSQL and JavaScript: a Love Story
NoSQL and JavaScript: a Love StoryNoSQL and JavaScript: a Love Story
NoSQL and JavaScript: a Love Story
 
Python and MongoDB
Python and MongoDB Python and MongoDB
Python and MongoDB
 
What do you mean, Backwards Compatibility?
What do you mean, Backwards Compatibility?What do you mean, Backwards Compatibility?
What do you mean, Backwards Compatibility?
 
MongoDB and Python
MongoDB and PythonMongoDB and Python
MongoDB and Python
 
Map/Confused? A practical approach to Map/Reduce with MongoDB
Map/Confused? A practical approach to Map/Reduce with MongoDBMap/Confused? A practical approach to Map/Reduce with MongoDB
Map/Confused? A practical approach to Map/Reduce with MongoDB
 
DrupalCon Chicago Practical MongoDB and Drupal
DrupalCon Chicago Practical MongoDB and DrupalDrupalCon Chicago Practical MongoDB and Drupal
DrupalCon Chicago Practical MongoDB and Drupal
 
Benefits of Using MongoDB Over RDBMS (At An Evening with MongoDB Minneapolis ...
Benefits of Using MongoDB Over RDBMS (At An Evening with MongoDB Minneapolis ...Benefits of Using MongoDB Over RDBMS (At An Evening with MongoDB Minneapolis ...
Benefits of Using MongoDB Over RDBMS (At An Evening with MongoDB Minneapolis ...
 
MongoDB World 2016: Deciphering .explain() Output
MongoDB World 2016: Deciphering .explain() OutputMongoDB World 2016: Deciphering .explain() Output
MongoDB World 2016: Deciphering .explain() Output
 

Viewers also liked

Mongo sf easy java persistence
Mongo sf   easy java persistenceMongo sf   easy java persistence
Mongo sf easy java persistenceScott Hernandez
 
Introdução no sql mongodb java
Introdução no sql mongodb javaIntrodução no sql mongodb java
Introdução no sql mongodb javaFabiano Modos
 
Java driver for mongo db
Java driver for mongo dbJava driver for mongo db
Java driver for mongo dbAbhay Pai
 
What's new in the MongoDB Java Driver (2.5)?
What's new in the MongoDB Java Driver (2.5)?What's new in the MongoDB Java Driver (2.5)?
What's new in the MongoDB Java Driver (2.5)?Scott Hernandez
 
Introducing Hibernate OGM: porting JPA applications to NoSQL, Sanne Grinovero...
Introducing Hibernate OGM: porting JPA applications to NoSQL, Sanne Grinovero...Introducing Hibernate OGM: porting JPA applications to NoSQL, Sanne Grinovero...
Introducing Hibernate OGM: porting JPA applications to NoSQL, Sanne Grinovero...OpenBlend society
 
Get expertise with mongo db
Get expertise with mongo dbGet expertise with mongo db
Get expertise with mongo dbAmit Thakkar
 
Using JPA applications in the era of NoSQL: Introducing Hibernate OGM
Using JPA applications in the era of NoSQL: Introducing Hibernate OGMUsing JPA applications in the era of NoSQL: Introducing Hibernate OGM
Using JPA applications in the era of NoSQL: Introducing Hibernate OGMPT.JUG
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDBJustin Smestad
 
JSON-LD for RESTful services
JSON-LD for RESTful servicesJSON-LD for RESTful services
JSON-LD for RESTful servicesMarkus Lanthaler
 
Building Next-Generation Web APIs with JSON-LD and Hydra
Building Next-Generation Web APIs with JSON-LD and HydraBuilding Next-Generation Web APIs with JSON-LD and Hydra
Building Next-Generation Web APIs with JSON-LD and HydraMarkus Lanthaler
 
MongoDB for Beginners
MongoDB for BeginnersMongoDB for Beginners
MongoDB for BeginnersEnoch Joshua
 
Intro To MongoDB
Intro To MongoDBIntro To MongoDB
Intro To MongoDBAlex Sharp
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDBRavi Teja
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDBMike Dirolf
 
MongoDB Java Development - MongoBoston 2010
MongoDB Java Development - MongoBoston 2010MongoDB Java Development - MongoBoston 2010
MongoDB Java Development - MongoBoston 2010Eliot Horowitz
 

Viewers also liked (20)

Mongo sf easy java persistence
Mongo sf   easy java persistenceMongo sf   easy java persistence
Mongo sf easy java persistence
 
Introdução no sql mongodb java
Introdução no sql mongodb javaIntrodução no sql mongodb java
Introdução no sql mongodb java
 
Java driver for mongo db
Java driver for mongo dbJava driver for mongo db
Java driver for mongo db
 
What's new in the MongoDB Java Driver (2.5)?
What's new in the MongoDB Java Driver (2.5)?What's new in the MongoDB Java Driver (2.5)?
What's new in the MongoDB Java Driver (2.5)?
 
Introducing Hibernate OGM: porting JPA applications to NoSQL, Sanne Grinovero...
Introducing Hibernate OGM: porting JPA applications to NoSQL, Sanne Grinovero...Introducing Hibernate OGM: porting JPA applications to NoSQL, Sanne Grinovero...
Introducing Hibernate OGM: porting JPA applications to NoSQL, Sanne Grinovero...
 
Get expertise with mongo db
Get expertise with mongo dbGet expertise with mongo db
Get expertise with mongo db
 
Using JPA applications in the era of NoSQL: Introducing Hibernate OGM
Using JPA applications in the era of NoSQL: Introducing Hibernate OGMUsing JPA applications in the era of NoSQL: Introducing Hibernate OGM
Using JPA applications in the era of NoSQL: Introducing Hibernate OGM
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
JSON-LD for RESTful services
JSON-LD for RESTful servicesJSON-LD for RESTful services
JSON-LD for RESTful services
 
#2 JSON Overview
#2   JSON Overview #2   JSON Overview
#2 JSON Overview
 
JSON-LD and MongoDB
JSON-LD and MongoDBJSON-LD and MongoDB
JSON-LD and MongoDB
 
Building Next-Generation Web APIs with JSON-LD and Hydra
Building Next-Generation Web APIs with JSON-LD and HydraBuilding Next-Generation Web APIs with JSON-LD and Hydra
Building Next-Generation Web APIs with JSON-LD and Hydra
 
MongoDB for Beginners
MongoDB for BeginnersMongoDB for Beginners
MongoDB for Beginners
 
Mongo DB
Mongo DBMongo DB
Mongo DB
 
Mongo db
Mongo dbMongo db
Mongo db
 
Intro To MongoDB
Intro To MongoDBIntro To MongoDB
Intro To MongoDB
 
Mongo DB
Mongo DBMongo DB
Mongo DB
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
MongoDB Java Development - MongoBoston 2010
MongoDB Java Development - MongoBoston 2010MongoDB Java Development - MongoBoston 2010
MongoDB Java Development - MongoBoston 2010
 

Similar to Java Development with MongoDB - An Overview

Java Development with MongoDB (James Williams)
Java Development with MongoDB (James Williams)Java Development with MongoDB (James Williams)
Java Development with MongoDB (James Williams)MongoSF
 
An introduction into Spring Data
An introduction into Spring DataAn introduction into Spring Data
An introduction into Spring DataOliver Gierke
 
Data access 2.0? Please welcome: Spring Data!
Data access 2.0? Please welcome: Spring Data!Data access 2.0? Please welcome: Spring Data!
Data access 2.0? Please welcome: Spring Data!Oliver Gierke
 
Spring Data MongoDB 介紹
Spring Data MongoDB 介紹Spring Data MongoDB 介紹
Spring Data MongoDB 介紹Kuo-Chun Su
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDBAlex Bilbie
 
Using MongoDB With Groovy
Using MongoDB With GroovyUsing MongoDB With Groovy
Using MongoDB With GroovyJames Williams
 
San Francisco Java User Group
San Francisco Java User GroupSan Francisco Java User Group
San Francisco Java User Groupkchodorow
 
Introduction to NOSQL And MongoDB
Introduction to NOSQL And MongoDBIntroduction to NOSQL And MongoDB
Introduction to NOSQL And MongoDBBehrouz Bakhtiari
 
Sekilas PHP + mongoDB
Sekilas PHP + mongoDBSekilas PHP + mongoDB
Sekilas PHP + mongoDBHadi Ariawan
 
Spray Json and MongoDB Queries: Insights and Simple Tricks.
Spray Json and MongoDB Queries: Insights and Simple Tricks.Spray Json and MongoDB Queries: Insights and Simple Tricks.
Spray Json and MongoDB Queries: Insights and Simple Tricks.Andrii Lashchenko
 
REST Web API with MongoDB
REST Web API with MongoDBREST Web API with MongoDB
REST Web API with MongoDBMongoDB
 
This upload requires better support for ODP format
This upload requires better support for ODP formatThis upload requires better support for ODP format
This upload requires better support for ODP formatForest Mars
 
How to use MongoDB with CakePHP
How to use MongoDB with CakePHPHow to use MongoDB with CakePHP
How to use MongoDB with CakePHPichikaway
 
Entity Framework: Nakov @ BFU Hackhaton 2015
Entity Framework: Nakov @ BFU Hackhaton 2015Entity Framework: Nakov @ BFU Hackhaton 2015
Entity Framework: Nakov @ BFU Hackhaton 2015Svetlin Nakov
 

Similar to Java Development with MongoDB - An Overview (20)

Java Development with MongoDB (James Williams)
Java Development with MongoDB (James Williams)Java Development with MongoDB (James Williams)
Java Development with MongoDB (James Williams)
 
An introduction into Spring Data
An introduction into Spring DataAn introduction into Spring Data
An introduction into Spring Data
 
Data access 2.0? Please welcome: Spring Data!
Data access 2.0? Please welcome: Spring Data!Data access 2.0? Please welcome: Spring Data!
Data access 2.0? Please welcome: Spring Data!
 
Spring Data MongoDB 介紹
Spring Data MongoDB 介紹Spring Data MongoDB 介紹
Spring Data MongoDB 介紹
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
Mongo learning series
Mongo learning series Mongo learning series
Mongo learning series
 
Using MongoDB With Groovy
Using MongoDB With GroovyUsing MongoDB With Groovy
Using MongoDB With Groovy
 
San Francisco Java User Group
San Francisco Java User GroupSan Francisco Java User Group
San Francisco Java User Group
 
Introduction to NOSQL And MongoDB
Introduction to NOSQL And MongoDBIntroduction to NOSQL And MongoDB
Introduction to NOSQL And MongoDB
 
Mongo-Drupal
Mongo-DrupalMongo-Drupal
Mongo-Drupal
 
Sekilas PHP + mongoDB
Sekilas PHP + mongoDBSekilas PHP + mongoDB
Sekilas PHP + mongoDB
 
Spray Json and MongoDB Queries: Insights and Simple Tricks.
Spray Json and MongoDB Queries: Insights and Simple Tricks.Spray Json and MongoDB Queries: Insights and Simple Tricks.
Spray Json and MongoDB Queries: Insights and Simple Tricks.
 
Latinoware
LatinowareLatinoware
Latinoware
 
REST Web API with MongoDB
REST Web API with MongoDBREST Web API with MongoDB
REST Web API with MongoDB
 
Green dao
Green daoGreen dao
Green dao
 
This upload requires better support for ODP format
This upload requires better support for ODP formatThis upload requires better support for ODP format
This upload requires better support for ODP format
 
How to use MongoDB with CakePHP
How to use MongoDB with CakePHPHow to use MongoDB with CakePHP
How to use MongoDB with CakePHP
 
MongoDB
MongoDBMongoDB
MongoDB
 
ExSchema
ExSchemaExSchema
ExSchema
 
Entity Framework: Nakov @ BFU Hackhaton 2015
Entity Framework: Nakov @ BFU Hackhaton 2015Entity Framework: Nakov @ BFU Hackhaton 2015
Entity Framework: Nakov @ BFU Hackhaton 2015
 

More from James Williams

Introduction to WebGL and Three.js
Introduction to WebGL and Three.jsIntroduction to WebGL and Three.js
Introduction to WebGL and Three.jsJames Williams
 
Intro to HTML5 Game Programming
Intro to HTML5 Game ProgrammingIntro to HTML5 Game Programming
Intro to HTML5 Game ProgrammingJames Williams
 
Ratpack - Classy and Compact Groovy Web Apps
Ratpack - Classy and Compact Groovy Web AppsRatpack - Classy and Compact Groovy Web Apps
Ratpack - Classy and Compact Groovy Web AppsJames Williams
 
Introduction to Griffon
Introduction to GriffonIntroduction to Griffon
Introduction to GriffonJames Williams
 
Griffon for the Enterprise
Griffon for the EnterpriseGriffon for the Enterprise
Griffon for the EnterpriseJames Williams
 
Game programming with Groovy
Game programming with GroovyGame programming with Groovy
Game programming with GroovyJames Williams
 
Porting legacy apps to Griffon
Porting legacy apps to GriffonPorting legacy apps to Griffon
Porting legacy apps to GriffonJames Williams
 
Creating Voice Powered Apps with Ribbit
Creating Voice Powered Apps with RibbitCreating Voice Powered Apps with Ribbit
Creating Voice Powered Apps with RibbitJames Williams
 
Griffon: Swing just got fun again
Griffon: Swing just got fun againGriffon: Swing just got fun again
Griffon: Swing just got fun againJames Williams
 
Griffon: Swing just got fun again
Griffon: Swing just got fun againGriffon: Swing just got fun again
Griffon: Swing just got fun againJames Williams
 
Extending Groovys Swing User Interface in Builder to Build Richer Applications
Extending Groovys Swing User Interface in Builder to Build Richer ApplicationsExtending Groovys Swing User Interface in Builder to Build Richer Applications
Extending Groovys Swing User Interface in Builder to Build Richer ApplicationsJames Williams
 
Boosting Your Testing Productivity with Groovy
Boosting Your Testing Productivity with GroovyBoosting Your Testing Productivity with Groovy
Boosting Your Testing Productivity with GroovyJames Williams
 
Griffon: Re-imaging Desktop Java Technology
Griffon: Re-imaging Desktop Java TechnologyGriffon: Re-imaging Desktop Java Technology
Griffon: Re-imaging Desktop Java TechnologyJames Williams
 

More from James Williams (16)

Introduction to WebGL and Three.js
Introduction to WebGL and Three.jsIntroduction to WebGL and Three.js
Introduction to WebGL and Three.js
 
Intro to HTML5 Game Programming
Intro to HTML5 Game ProgrammingIntro to HTML5 Game Programming
Intro to HTML5 Game Programming
 
Ratpack - Classy and Compact Groovy Web Apps
Ratpack - Classy and Compact Groovy Web AppsRatpack - Classy and Compact Groovy Web Apps
Ratpack - Classy and Compact Groovy Web Apps
 
Introduction to Griffon
Introduction to GriffonIntroduction to Griffon
Introduction to Griffon
 
Griffon for the Enterprise
Griffon for the EnterpriseGriffon for the Enterprise
Griffon for the Enterprise
 
Game programming with Groovy
Game programming with GroovyGame programming with Groovy
Game programming with Groovy
 
Enterprise Griffon
Enterprise GriffonEnterprise Griffon
Enterprise Griffon
 
Porting legacy apps to Griffon
Porting legacy apps to GriffonPorting legacy apps to Griffon
Porting legacy apps to Griffon
 
Creating Voice Powered Apps with Ribbit
Creating Voice Powered Apps with RibbitCreating Voice Powered Apps with Ribbit
Creating Voice Powered Apps with Ribbit
 
Griffon: Swing just got fun again
Griffon: Swing just got fun againGriffon: Swing just got fun again
Griffon: Swing just got fun again
 
Griffon: Swing just got fun again
Griffon: Swing just got fun againGriffon: Swing just got fun again
Griffon: Swing just got fun again
 
Extending Groovys Swing User Interface in Builder to Build Richer Applications
Extending Groovys Swing User Interface in Builder to Build Richer ApplicationsExtending Groovys Swing User Interface in Builder to Build Richer Applications
Extending Groovys Swing User Interface in Builder to Build Richer Applications
 
Boosting Your Testing Productivity with Groovy
Boosting Your Testing Productivity with GroovyBoosting Your Testing Productivity with Groovy
Boosting Your Testing Productivity with Groovy
 
Griffon: Re-imaging Desktop Java Technology
Griffon: Re-imaging Desktop Java TechnologyGriffon: Re-imaging Desktop Java Technology
Griffon: Re-imaging Desktop Java Technology
 
Android Development
Android DevelopmentAndroid Development
Android Development
 
SVCC Intro to Grails
SVCC Intro to GrailsSVCC Intro to Grails
SVCC Intro to Grails
 

Recently uploaded

Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 

Recently uploaded (20)

Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 

Java Development with MongoDB - An Overview

  • 1. Java Development with MongoDB James Williams Software Engineer, BT/Ribbit
  • 2. Agenda Java Driver basics Making Connections Managing Collections BasicDBObjectBuilder Document Queries GridFS Morphia Beyond the Java language Groovy utilities Grails plugin
  • 3. Making a Connection import com.mongodb.Mongo; import com.mongodb.DB; Mongo m = new Mongo(); Mongo m = new Mongo( "localhost" ); Mongo m = new Mongo( "localhost" , 27017 ); DB db = m.getDB( "mydb" );
  • 4. Working with Collections Getting all collections in the database Set<String> colls = db.getCollectionNames(); for (String s : colls) { System.out.println(s); } Getting a single collection DBCollection coll = db.getCollection("testCollection")
  • 5. Inserting Documents BasicDBObject doc = new BasicDBObject(); doc.put("name", "MongoDB"); doc.put("type", "database"); doc.put("count", 1); BasicDBObject info = new BasicDBObject(); info.put("x", 203); info.put("y", 102); doc.put("info", info); coll.insert(doc);
  • 6. BasicDBObjectBuilder Utility for building objects Can coerce Maps (and possibly JSON*) to DBObjects Example: BasicDBObjectBuilder.start() .add( "name" , "eliot" ) .add( "number" , 17 ) .get();
  • 7. Document Queries DBObject myDoc = coll.findOne(); // can also use BasicDBObject query = new BasicDBObject(); query.put("i", 71); DBCursor cur = coll.find(query);
  • 8. GridFS mechanism for storing files larger than 4MB files are chunked allowing fetching of a portion or out of order chunking is mostly transparent to underlying operating system can store files in buckets, a MongoDB metaphor for folders default is the fs bucket
  • 9. Saving a file to GridFS def mongo = new Mongo(host) def gridfs = new GridFS(mongo.getDB("db")) def save(inputStream, contentType, filename) { def inputFile = gridfs.createFile(inputStream) inputFile.setContentType(contentType) inputFile.setFilename(filename) inputFile.save() }
  • 10. Retrieving/Deleting a file def retrieveFile(String filename) { return gridfs.findOne(filename) } def deleteFile(String filename) { gridfs.remove(filename) }
  • 11. Morphia Apache 2 Licensed brings Hibernate/JPA paradigms to MongoDB allows annotating of POJOs to make converting them between MongoDB and Java very easy supports DAO abstractions offers type-safe query support compatible with GWT, Guice, Spring, and DI frameworks
  • 12. Morphia Annotations @Id @Entity @Embedded @Reference @Indexed @Serialized @Property
  • 13. Creating a Morphia POJO import com.google.code.morphia.annotations.*; @Entity("collectionName") public class Contact { @Id private String id; //generated by MongoDB private String firstName; private String lastName; @Embedded private List<PhoneNumber> phoneNumbers; // getters and setters }
  • 14. Mapping a POJO to a Mongo doc Morphia morphia = ...; Mongo mongo = ...; DB db = mongo.getDB("contacts"); Contact contact = ...; // map the contact to a DBObject DBObject contactObj = morphia.toDBObject(contact); db.getCollection("personal").save(contactObj);
  • 15. Getting a POJO from a Mongo doc Morphia morphia = ...; Mongo mongo = ...; DB db = mongo.getDB("contacts"); String contactId = ...; //load the object from the collection BasicDBObject idObj = new BasicDBObject( "_id", new ObjectId(contactId) ); BasicDBObject obj = (BasicDBObject) db.getCollection("personal").findOne(idObj); Contact contact = morphia.fromDBObject(Contact.class, obj);
  • 16. DAOs Encapsulate saving and retrieving objects Auto-converts to and from POJOs Can provide constraints on searches Key functions: get(<mongoId>) find() or find(constraints) findOne(constraints) deleteById(<mongoId>)
  • 17. DAO Example import com.mongodb.Mongo import com.google.code.morphia.* class EntryDAO extends DAO<BlogEntry,String> { public EntryDAO(Morphia morphia, Mongo mongo) { super(mongo, morphia, "entries") } }
  • 18. Constraints Examples dao.find(new Constraints() . orderByDesc("dateCreated") ).asList() dao.find( new Constraints() .field("dateCreated").greaterThanOrEqualTo(date).field("title"). equalTo(params.title) ).asList()
  • 19. Beyond the Java Language
  • 20. MongoDB with Groovy Metaprogramming with MongoDB can reduce LOC Dynamic finders Fluent interface mirroring Ruby and Python
  • 21. Groovy + MongoDB Java BasicDBObject doc = new BasicDBObject(); doc.put("name", "MongoDB"); doc.put("type", "database"); doc.put("count", 1); coll.insert(doc); Groovier def doc = [name:"MongoDB",type:"database", count:1, info: [x:203, y:102] ] as BasicDBObject coll.insert(doc) Grooviest (using groovy-mongo) coll.insert([name:"MongoDB", type:"database", info: [x:203, y:102]])
  • 22. Dynamic Finders can build complex queries at runtime can even reach into objects for addition query parameters Ex. collection.findByAuthorAndPostCreatedGreaterThan(...) collection.findByComments_CreatedOn(...)
  • 23. How dynamic finders work Groovy receives the request for the method The method is not found (invoking methodMissing) The method name used to construct a query template The method is cached The method is invoked with the parameters Future invocations use the cached method
  • 24. MongoDB Grails Plugin Replaces JDBC layer in Grails applications Can use dynamic finders Requires only slight modifications to domain classes http://github.com/mpriatel/mongodb-grails
  • 25. Links Personal Blog: http://jameswilliams.be/blog Twitter: http://twitter.com/ecspike Morphia: http://code.google.com/p/morphia Utilities for Groovy: http://github.com/jwill/groovy-mongo MongoDB Grails plugin: http://github. com/mpriatel/mongodb-grails