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
Ad

Recommended

Java Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDB
MongoDB
 
MongoDB + Java + Spring Data
MongoDB + Java + Spring Data
Anton Sulzhenko
 
Morphia: Simplifying Persistence for Java and MongoDB
Morphia: Simplifying Persistence for Java and MongoDB
Jeff Yemin
 
Java Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDB
Tobias Trelle
 
Morphia, Spring Data & Co.
Morphia, Spring Data & Co.
Tobias Trelle
 
Java Development with MongoDB
Java Development with MongoDB
Scott Hernandez
 
Simplifying Persistence for Java and MongoDB with Morphia
Simplifying Persistence for Java and MongoDB with Morphia
MongoDB
 
MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know
Norberto Leite
 
MongoDB: Easy Java Persistence with Morphia
MongoDB: Easy Java Persistence with Morphia
Scott Hernandez
 
Spring Data, Jongo & Co.
Spring Data, Jongo & Co.
Tobias Trelle
 
Webinar: MongoDB Persistence with Java and Morphia
Webinar: MongoDB Persistence with Java and Morphia
MongoDB
 
Getting Started with MongoDB and NodeJS
Getting Started with MongoDB and NodeJS
MongoDB
 
Indexing
Indexing
Mike Dirolf
 
Webinar: Building Your First App with MongoDB and Java
Webinar: Building Your First App with MongoDB and Java
MongoDB
 
Real World Application Performance with MongoDB
Real World Application Performance with MongoDB
MongoDB
 
Back to Basics Webinar 5: Introduction to the Aggregation Framework
Back to Basics Webinar 5: Introduction to the Aggregation Framework
MongoDB
 
BedCon 2013 - Java Persistenz-Frameworks für MongoDB
BedCon 2013 - Java Persistenz-Frameworks für MongoDB
Tobias Trelle
 
CouchDB on Android
CouchDB on Android
Sven Haiges
 
NoSQL and JavaScript: a Love Story
NoSQL and JavaScript: a Love Story
Alexandre Morgaut
 
Python and MongoDB
Python and MongoDB
Norberto Leite
 
What do you mean, Backwards Compatibility?
What do you mean, Backwards Compatibility?
Trisha Gee
 
MongoDB and Python
MongoDB and Python
Norberto Leite
 
Map/Confused? A practical approach to Map/Reduce with MongoDB
Map/Confused? A practical approach to Map/Reduce with MongoDB
Uwe Printz
 
DrupalCon Chicago Practical MongoDB and Drupal
DrupalCon Chicago Practical MongoDB and Drupal
Doug 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 ...
MongoDB
 
MongoDB World 2016: Deciphering .explain() Output
MongoDB World 2016: Deciphering .explain() Output
MongoDB
 
Mongo sf easy java persistence
Mongo sf easy java persistence
Scott Hernandez
 
Introdução no sql mongodb java
Introdução no sql mongodb java
Fabiano Modos
 
Java driver for mongo db
Java driver for mongo db
Abhay Pai
 
What's new in the MongoDB Java Driver (2.5)?
What's new in the MongoDB Java Driver (2.5)?
Scott Hernandez
 

More Related Content

What's hot (18)

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

Viewers also liked (20)

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

Similar to Java development with MongoDB (20)

Java Development with MongoDB (James Williams)
Java Development with MongoDB (James Williams)
MongoSF
 
MongoDB using Grails plugin by puneet behl
MongoDB using Grails plugin by puneet behl
TO THE NEW | Technology
 
Using MongoDB With Groovy
Using MongoDB With Groovy
James Williams
 
Mongodb Introduction
Mongodb Introduction
Nabeel Naqeebi
 
Introduction to MongoDB
Introduction to MongoDB
S.Shayan Daneshvar
 
MongoDB presentation
MongoDB presentation
Hyphen Call
 
Mongodb
Mongodb
SARAVANAN GOPALAKRISHNAN
 
Dev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDB
MongoDB
 
MongoDB
MongoDB
Anthony Slabinck
 
MongoDB + Spring
MongoDB + Spring
Norberto Leite
 
MongoDB and Spring - Two leaves of a same tree
MongoDB and Spring - Two leaves of a same tree
MongoDB
 
Mongo db nosql (1)
Mongo db nosql (1)
Bhavesh Sarvaiya
 
Building your first app with MongoDB
Building your first app with MongoDB
Norberto Leite
 
Getting started with MongoDB and Scala - Open Source Bridge 2012
Getting started with MongoDB and Scala - Open Source Bridge 2012
sullis
 
MongoDB introduction features -presentation - 2.pptx
MongoDB introduction features -presentation - 2.pptx
sampathkumar546444
 
MongoDB DOC v1.5
MongoDB DOC v1.5
Tharun Srinivasa
 
MongoDB_ppt.pptx
MongoDB_ppt.pptx
1AP18CS037ShirishKul
 
Getting Started with MongoDB (TCF ITPC 2014)
Getting Started with MongoDB (TCF ITPC 2014)
Michael Redlich
 
3-Mongodb and Mapreduce Programming.pdf
3-Mongodb and Mapreduce Programming.pdf
MarianJRuben
 
Mongo db operations_v2
Mongo db operations_v2
Thanabalan Sathneeganandan
 
Java Development with MongoDB (James Williams)
Java Development with MongoDB (James Williams)
MongoSF
 
MongoDB using Grails plugin by puneet behl
MongoDB using Grails plugin by puneet behl
TO THE NEW | Technology
 
Using MongoDB With Groovy
Using MongoDB With Groovy
James Williams
 
MongoDB presentation
MongoDB presentation
Hyphen Call
 
Dev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDB
MongoDB
 
MongoDB and Spring - Two leaves of a same tree
MongoDB and Spring - Two leaves of a same tree
MongoDB
 
Building your first app with MongoDB
Building your first app with MongoDB
Norberto Leite
 
Getting started with MongoDB and Scala - Open Source Bridge 2012
Getting started with MongoDB and Scala - Open Source Bridge 2012
sullis
 
MongoDB introduction features -presentation - 2.pptx
MongoDB introduction features -presentation - 2.pptx
sampathkumar546444
 
Getting Started with MongoDB (TCF ITPC 2014)
Getting Started with MongoDB (TCF ITPC 2014)
Michael Redlich
 
3-Mongodb and Mapreduce Programming.pdf
3-Mongodb and Mapreduce Programming.pdf
MarianJRuben
 
Ad

More from James Williams (16)

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

Recently uploaded (20)

Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
June Patch Tuesday
June Patch Tuesday
Ivanti
 
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Alliance
 
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Safe Software
 
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Alliance
 
MuleSoft for AgentForce : Topic Center and API Catalog
MuleSoft for AgentForce : Topic Center and API Catalog
shyamraj55
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
Safe Software
 
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
SOFTTECHHUB
 
High Availability On-Premises FME Flow.pdf
High Availability On-Premises FME Flow.pdf
Safe Software
 
Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 
“Why It’s Critical to Have an Integrated Development Methodology for Edge AI,...
“Why It’s Critical to Have an Integrated Development Methodology for Edge AI,...
Edge AI and Vision Alliance
 
Murdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementary
JorgeSemperteguiMont
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
AmirStern2
 
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
NTT DATA Technology & Innovation
 
Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
“Addressing Evolving AI Model Challenges Through Memory and Storage,” a Prese...
“Addressing Evolving AI Model Challenges Through Memory and Storage,” a Prese...
Edge AI and Vision Alliance
 
FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)
FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)
Safe Software
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
June Patch Tuesday
June Patch Tuesday
Ivanti
 
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Alliance
 
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Safe Software
 
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Alliance
 
MuleSoft for AgentForce : Topic Center and API Catalog
MuleSoft for AgentForce : Topic Center and API Catalog
shyamraj55
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
Safe Software
 
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
SOFTTECHHUB
 
High Availability On-Premises FME Flow.pdf
High Availability On-Premises FME Flow.pdf
Safe Software
 
Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 
“Why It’s Critical to Have an Integrated Development Methodology for Edge AI,...
“Why It’s Critical to Have an Integrated Development Methodology for Edge AI,...
Edge AI and Vision Alliance
 
Murdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementary
JorgeSemperteguiMont
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
AmirStern2
 
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
NTT DATA Technology & Innovation
 
Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
“Addressing Evolving AI Model Challenges Through Memory and Storage,” a Prese...
“Addressing Evolving AI Model Challenges Through Memory and Storage,” a Prese...
Edge AI and Vision Alliance
 
FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)
FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)
Safe Software
 

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