SlideShare a Scribd company logo
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 (18)

PPTX
MongoDB: Easy Java Persistence with Morphia
Scott Hernandez
 
PPTX
Spring Data, Jongo & Co.
Tobias Trelle
 
PDF
Webinar: MongoDB Persistence with Java and Morphia
MongoDB
 
PPTX
Getting Started with MongoDB and NodeJS
MongoDB
 
PDF
Indexing
Mike Dirolf
 
PDF
Webinar: Building Your First App with MongoDB and Java
MongoDB
 
PPT
Real World Application Performance with MongoDB
MongoDB
 
PPTX
Back to Basics Webinar 5: Introduction to the Aggregation Framework
MongoDB
 
PPTX
BedCon 2013 - Java Persistenz-Frameworks für MongoDB
Tobias Trelle
 
KEY
CouchDB on Android
Sven Haiges
 
PDF
NoSQL and JavaScript: a Love Story
Alexandre Morgaut
 
PDF
Python and MongoDB
Norberto Leite
 
PDF
What do you mean, Backwards Compatibility?
Trisha Gee
 
PDF
MongoDB and Python
Norberto Leite
 
PDF
Map/Confused? A practical approach to Map/Reduce with MongoDB
Uwe Printz
 
ODP
DrupalCon Chicago Practical MongoDB and Drupal
Doug Green
 
PPTX
Benefits of Using MongoDB Over RDBMS (At An Evening with MongoDB Minneapolis ...
MongoDB
 
PDF
MongoDB World 2016: Deciphering .explain() Output
MongoDB
 
MongoDB: Easy Java Persistence with Morphia
Scott Hernandez
 
Spring Data, Jongo & Co.
Tobias Trelle
 
Webinar: MongoDB Persistence with Java and Morphia
MongoDB
 
Getting Started with MongoDB and NodeJS
MongoDB
 
Indexing
Mike Dirolf
 
Webinar: Building Your First App with MongoDB and Java
MongoDB
 
Real World Application Performance with MongoDB
MongoDB
 
Back to Basics Webinar 5: Introduction to the Aggregation Framework
MongoDB
 
BedCon 2013 - Java Persistenz-Frameworks für MongoDB
Tobias Trelle
 
CouchDB on Android
Sven Haiges
 
NoSQL and JavaScript: a Love Story
Alexandre Morgaut
 
Python and MongoDB
Norberto Leite
 
What do you mean, Backwards Compatibility?
Trisha Gee
 
MongoDB and Python
Norberto Leite
 
Map/Confused? A practical approach to Map/Reduce with MongoDB
Uwe Printz
 
DrupalCon Chicago Practical MongoDB and Drupal
Doug Green
 
Benefits of Using MongoDB Over RDBMS (At An Evening with MongoDB Minneapolis ...
MongoDB
 
MongoDB World 2016: Deciphering .explain() Output
MongoDB
 

Viewers also liked (20)

PPTX
Mongo sf easy java persistence
Scott Hernandez
 
PPTX
Introdução no sql mongodb java
Fabiano Modos
 
PPTX
Java driver for mongo db
Abhay Pai
 
PPTX
What's new in the MongoDB Java Driver (2.5)?
Scott Hernandez
 
PDF
Introducing Hibernate OGM: porting JPA applications to NoSQL, Sanne Grinovero...
OpenBlend society
 
PPTX
Get expertise with mongo db
Amit Thakkar
 
PDF
Using JPA applications in the era of NoSQL: Introducing Hibernate OGM
PT.JUG
 
PDF
Introduction to MongoDB
Justin Smestad
 
PPTX
JSON-LD for RESTful services
Markus Lanthaler
 
PPTX
#2 JSON Overview
Gabriel Alves Scavassa
 
KEY
JSON-LD and MongoDB
Gregg Kellogg
 
PPTX
Building Next-Generation Web APIs with JSON-LD and Hydra
Markus Lanthaler
 
PPTX
MongoDB for Beginners
Enoch Joshua
 
PPTX
Mongo DB
Karan Kukreja
 
PPTX
Mongo db
Akshay Mathur
 
PDF
Intro To MongoDB
Alex Sharp
 
PDF
Mongo DB
Edureka!
 
PPT
Introduction to MongoDB
Ravi Teja
 
PDF
Introduction to MongoDB
Mike Dirolf
 
KEY
MongoDB Java Development - MongoBoston 2010
Eliot Horowitz
 
Mongo sf easy java persistence
Scott Hernandez
 
Introdução no sql mongodb java
Fabiano Modos
 
Java driver for mongo db
Abhay Pai
 
What's new in the MongoDB Java Driver (2.5)?
Scott Hernandez
 
Introducing Hibernate OGM: porting JPA applications to NoSQL, Sanne Grinovero...
OpenBlend society
 
Get expertise with mongo db
Amit Thakkar
 
Using JPA applications in the era of NoSQL: Introducing Hibernate OGM
PT.JUG
 
Introduction to MongoDB
Justin Smestad
 
JSON-LD for RESTful services
Markus Lanthaler
 
#2 JSON Overview
Gabriel Alves Scavassa
 
JSON-LD and MongoDB
Gregg Kellogg
 
Building Next-Generation Web APIs with JSON-LD and Hydra
Markus Lanthaler
 
MongoDB for Beginners
Enoch Joshua
 
Mongo DB
Karan Kukreja
 
Mongo db
Akshay Mathur
 
Intro To MongoDB
Alex Sharp
 
Mongo DB
Edureka!
 
Introduction to MongoDB
Ravi Teja
 
Introduction to MongoDB
Mike Dirolf
 
MongoDB Java Development - MongoBoston 2010
Eliot Horowitz
 
Ad

Similar to Java development with MongoDB (20)

PPT
Java Development with MongoDB (James Williams)
MongoSF
 
PDF
An introduction into Spring Data
Oliver Gierke
 
PDF
Data access 2.0? Please welcome: Spring Data!
Oliver Gierke
 
PDF
Spring Data MongoDB 介紹
Kuo-Chun Su
 
KEY
Introduction to MongoDB
Alex Bilbie
 
PDF
Mongo learning series
Prashanth Panduranga
 
PPT
Using MongoDB With Groovy
James Williams
 
PDF
San Francisco Java User Group
kchodorow
 
PPTX
Introduction to NOSQL And MongoDB
Behrouz Bakhtiari
 
PPT
Mongo-Drupal
Forest Mars
 
PPTX
Sekilas PHP + mongoDB
Hadi Ariawan
 
PDF
Spray Json and MongoDB Queries: Insights and Simple Tricks.
Andrii Lashchenko
 
PDF
Latinoware
kchodorow
 
PDF
REST Web API with MongoDB
MongoDB
 
PDF
Green dao
Droidcon Berlin
 
ODP
This upload requires better support for ODP format
Forest Mars
 
PDF
How to use MongoDB with CakePHP
ichikaway
 
PPTX
MongoDB
nikhil2807
 
PPTX
ExSchema
jccastrejon
 
PPTX
Entity Framework: Nakov @ BFU Hackhaton 2015
Svetlin Nakov
 
Java Development with MongoDB (James Williams)
MongoSF
 
An introduction into Spring Data
Oliver Gierke
 
Data access 2.0? Please welcome: Spring Data!
Oliver Gierke
 
Spring Data MongoDB 介紹
Kuo-Chun Su
 
Introduction to MongoDB
Alex Bilbie
 
Mongo learning series
Prashanth Panduranga
 
Using MongoDB With Groovy
James Williams
 
San Francisco Java User Group
kchodorow
 
Introduction to NOSQL And MongoDB
Behrouz Bakhtiari
 
Mongo-Drupal
Forest Mars
 
Sekilas PHP + mongoDB
Hadi Ariawan
 
Spray Json and MongoDB Queries: Insights and Simple Tricks.
Andrii Lashchenko
 
Latinoware
kchodorow
 
REST Web API with MongoDB
MongoDB
 
Green dao
Droidcon Berlin
 
This upload requires better support for ODP format
Forest Mars
 
How to use MongoDB with CakePHP
ichikaway
 
MongoDB
nikhil2807
 
ExSchema
jccastrejon
 
Entity Framework: Nakov @ BFU Hackhaton 2015
Svetlin Nakov
 
Ad

More from James Williams (16)

KEY
Introduction to WebGL and Three.js
James Williams
 
PDF
Intro to HTML5 Game Programming
James Williams
 
PPT
Ratpack - Classy and Compact Groovy Web Apps
James Williams
 
PDF
Introduction to Griffon
James Williams
 
PDF
Griffon for the Enterprise
James Williams
 
PPT
Game programming with Groovy
James Williams
 
PDF
Enterprise Griffon
James Williams
 
PDF
Porting legacy apps to Griffon
James Williams
 
PDF
Creating Voice Powered Apps with Ribbit
James Williams
 
PDF
Griffon: Swing just got fun again
James Williams
 
PPT
Griffon: Swing just got fun again
James Williams
 
PPT
Extending Groovys Swing User Interface in Builder to Build Richer Applications
James Williams
 
PPT
Boosting Your Testing Productivity with Groovy
James Williams
 
ODP
Griffon: Re-imaging Desktop Java Technology
James Williams
 
ODP
Android Development
James Williams
 
ODP
SVCC Intro to Grails
James Williams
 
Introduction to WebGL and Three.js
James Williams
 
Intro to HTML5 Game Programming
James Williams
 
Ratpack - Classy and Compact Groovy Web Apps
James Williams
 
Introduction to Griffon
James Williams
 
Griffon for the Enterprise
James Williams
 
Game programming with Groovy
James Williams
 
Enterprise Griffon
James Williams
 
Porting legacy apps to Griffon
James Williams
 
Creating Voice Powered Apps with Ribbit
James Williams
 
Griffon: Swing just got fun again
James Williams
 
Griffon: Swing just got fun again
James Williams
 
Extending Groovys Swing User Interface in Builder to Build Richer Applications
James Williams
 
Boosting Your Testing Productivity with Groovy
James Williams
 
Griffon: Re-imaging Desktop Java Technology
James Williams
 
Android Development
James Williams
 
SVCC Intro to Grails
James Williams
 

Recently uploaded (20)

PDF
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
PDF
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
DOCX
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
PPTX
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PPTX
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PPTX
Digital Circuits, important subject in CS
contactparinay1
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
PDF
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PPTX
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
PDF
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
PDF
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
PDF
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
PDF
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
Digital Circuits, important subject in CS
contactparinay1
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 

Java development with MongoDB

  • 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