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

More Related Content

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
Scott 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 Morphia
MongoDB
 
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
Hermann Hueck
 
Getting Started with MongoDB and NodeJS
Getting Started with MongoDB and NodeJSGetting Started with MongoDB and NodeJS
Getting Started with MongoDB and NodeJS
MongoDB
 
Indexing
IndexingIndexing
Indexing
Mike Dirolf
 
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
MongoDB
 
Real World Application Performance with MongoDB
Real World Application Performance with MongoDBReal 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 FrameworkBack 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 MongoDBBedCon 2013 - Java Persistenz-Frameworks für MongoDB
BedCon 2013 - Java Persistenz-Frameworks für MongoDB
Tobias Trelle
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on Android
Sven Haiges
 
NoSQL and JavaScript: a Love Story
NoSQL and JavaScript: a Love StoryNoSQL and JavaScript: a Love Story
NoSQL and JavaScript: a Love Story
Alexandre Morgaut
 
Python and MongoDB
Python and MongoDB Python and MongoDB
Python and MongoDB
Norberto Leite
 
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
 
MongoDB and Python
MongoDB and PythonMongoDB 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 MongoDBMap/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 DrupalDrupalCon 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 ...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() Output
MongoDB
 
MongoDB: Easy Java Persistence with Morphia
MongoDB: Easy Java Persistence with MorphiaMongoDB: Easy Java Persistence with Morphia
MongoDB: Easy Java Persistence with Morphia
Scott 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 Morphia
MongoDB
 
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
Hermann Hueck
 
Getting Started with MongoDB and NodeJS
Getting Started with MongoDB and NodeJSGetting 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 JavaWebinar: 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 MongoDBReal 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 FrameworkBack 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 MongoDBBedCon 2013 - Java Persistenz-Frameworks für MongoDB
BedCon 2013 - Java Persistenz-Frameworks für MongoDB
Tobias Trelle
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on Android
Sven Haiges
 
NoSQL and JavaScript: a Love Story
NoSQL and JavaScript: a Love StoryNoSQL 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?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 MongoDB
Uwe Printz
 
DrupalCon Chicago Practical MongoDB and Drupal
DrupalCon Chicago Practical MongoDB and DrupalDrupalCon 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 ...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() Output
MongoDB
 

Viewers also liked (20)

Mongo sf easy java persistence
Mongo sf   easy java persistenceMongo sf   easy java persistence
Mongo sf easy java persistence
Scott Hernandez
 
Introdução no sql mongodb java
Introdução no sql mongodb javaIntrodução no sql mongodb java
Introdução no sql mongodb java
Fabiano Modos
 
Java driver for mongo db
Java driver for mongo dbJava 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)?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 db
Amit 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 OGM
PT.JUG
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
Justin Smestad
 
JSON-LD for RESTful services
JSON-LD for RESTful servicesJSON-LD for RESTful services
JSON-LD for RESTful services
Markus Lanthaler
 
#2 JSON Overview
#2   JSON Overview #2   JSON Overview
#2 JSON Overview
Gabriel Alves Scavassa
 
JSON-LD and MongoDB
JSON-LD and MongoDBJSON-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 HydraBuilding 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 BeginnersMongoDB for Beginners
MongoDB for Beginners
Enoch Joshua
 
Mongo DB
Mongo DBMongo DB
Mongo DB
Karan Kukreja
 
Mongo db
Mongo dbMongo db
Mongo db
Akshay Mathur
 
Intro To MongoDB
Intro To MongoDBIntro To MongoDB
Intro To MongoDB
Alex Sharp
 
Mongo DB
Mongo DBMongo DB
Mongo DB
Edureka!
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
Ravi Teja
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
Mike Dirolf
 
MongoDB Java Development - MongoBoston 2010
MongoDB Java Development - MongoBoston 2010MongoDB Java Development - MongoBoston 2010
MongoDB Java Development - MongoBoston 2010
Eliot Horowitz
 
Mongo sf easy java persistence
Mongo sf   easy java persistenceMongo sf   easy java persistence
Mongo sf easy java persistence
Scott Hernandez
 
Introdução no sql mongodb java
Introdução no sql mongodb javaIntrodução no sql mongodb java
Introdução no sql mongodb java
Fabiano Modos
 
Java driver for mongo db
Java driver for mongo dbJava 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)?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 db
Amit 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 OGM
PT.JUG
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
Justin Smestad
 
JSON-LD for RESTful services
JSON-LD for RESTful servicesJSON-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 HydraBuilding 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 BeginnersMongoDB for Beginners
MongoDB for Beginners
Enoch Joshua
 
Intro To MongoDB
Intro To MongoDBIntro To MongoDB
Intro To MongoDB
Alex Sharp
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
Ravi Teja
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
Mike Dirolf
 
MongoDB Java Development - MongoBoston 2010
MongoDB Java Development - MongoBoston 2010MongoDB 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)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 Data
Oliver 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 MongoDB
Alex Bilbie
 
Mongo learning series
Mongo learning series Mongo learning series
Mongo learning series
Prashanth Panduranga
 
Using MongoDB With Groovy
Using MongoDB With GroovyUsing MongoDB With Groovy
Using MongoDB With Groovy
James Williams
 
San Francisco Java User Group
San Francisco Java User GroupSan Francisco Java User Group
San Francisco Java User Group
kchodorow
 
Introduction to NOSQL And MongoDB
Introduction to NOSQL And MongoDBIntroduction to NOSQL And MongoDB
Introduction to NOSQL And MongoDB
Behrouz Bakhtiari
 
Mongo-Drupal
Mongo-DrupalMongo-Drupal
Mongo-Drupal
Forest Mars
 
Sekilas PHP + mongoDB
Sekilas PHP + mongoDBSekilas PHP + mongoDB
Sekilas PHP + mongoDB
Hadi 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
 
Latinoware
LatinowareLatinoware
Latinoware
kchodorow
 
REST Web API with MongoDB
REST Web API with MongoDBREST Web API with MongoDB
REST Web API with MongoDB
MongoDB
 
Green dao
Green daoGreen dao
Green dao
Droidcon Berlin
 
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
Forest Mars
 
How to use MongoDB with CakePHP
How to use MongoDB with CakePHPHow to use MongoDB with CakePHP
How to use MongoDB with CakePHP
ichikaway
 
MongoDB
MongoDBMongoDB
MongoDB
nikhil2807
 
ExSchema
ExSchemaExSchema
ExSchema
jccastrejon
 
Entity Framework: Nakov @ BFU Hackhaton 2015
Entity Framework: Nakov @ BFU Hackhaton 2015Entity Framework: Nakov @ BFU Hackhaton 2015
Entity Framework: Nakov @ BFU Hackhaton 2015
Svetlin Nakov
 
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 Data
Oliver 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 MongoDB
Alex Bilbie
 
Using MongoDB With Groovy
Using MongoDB With GroovyUsing MongoDB With Groovy
Using MongoDB With Groovy
James Williams
 
San Francisco Java User Group
San Francisco Java User GroupSan Francisco Java User Group
San Francisco Java User Group
kchodorow
 
Introduction to NOSQL And MongoDB
Introduction to NOSQL And MongoDBIntroduction to NOSQL And MongoDB
Introduction to NOSQL And MongoDB
Behrouz Bakhtiari
 
Sekilas PHP + mongoDB
Sekilas PHP + mongoDBSekilas PHP + mongoDB
Sekilas PHP + mongoDB
Hadi 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 MongoDB
MongoDB
 
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
Forest Mars
 
How to use MongoDB with CakePHP
How to use MongoDB with CakePHPHow to use MongoDB with CakePHP
How to use MongoDB with CakePHP
ichikaway
 
Entity Framework: Nakov @ BFU Hackhaton 2015
Entity Framework: Nakov @ BFU Hackhaton 2015Entity Framework: Nakov @ BFU Hackhaton 2015
Entity Framework: Nakov @ BFU Hackhaton 2015
Svetlin Nakov
 
Ad

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
James Williams
 
Intro to HTML5 Game Programming
Intro to HTML5 Game ProgrammingIntro to HTML5 Game Programming
Intro to HTML5 Game Programming
James 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 Apps
James Williams
 
Introduction to Griffon
Introduction to GriffonIntroduction to Griffon
Introduction to Griffon
James Williams
 
Griffon for the Enterprise
Griffon for the EnterpriseGriffon for the Enterprise
Griffon for the Enterprise
James Williams
 
Game programming with Groovy
Game programming with GroovyGame programming with Groovy
Game programming with Groovy
James Williams
 
Enterprise Griffon
Enterprise GriffonEnterprise Griffon
Enterprise Griffon
James Williams
 
Porting legacy apps to Griffon
Porting legacy apps to GriffonPorting legacy apps to Griffon
Porting legacy apps to Griffon
James Williams
 
Creating Voice Powered Apps with Ribbit
Creating Voice Powered Apps with RibbitCreating Voice Powered Apps with Ribbit
Creating Voice Powered Apps with Ribbit
James Williams
 
Griffon: Swing just got fun again
Griffon: Swing just got fun againGriffon: Swing just got fun again
Griffon: Swing just got fun again
James Williams
 
Griffon: Swing just got fun again
Griffon: Swing just got fun againGriffon: 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 ApplicationsExtending 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 GroovyBoosting Your Testing Productivity with Groovy
Boosting Your Testing Productivity with Groovy
James Williams
 
Griffon: Re-imaging Desktop Java Technology
Griffon: Re-imaging Desktop Java TechnologyGriffon: Re-imaging Desktop Java Technology
Griffon: Re-imaging Desktop Java Technology
James Williams
 
Android Development
Android DevelopmentAndroid Development
Android Development
James Williams
 
SVCC Intro to Grails
SVCC Intro to GrailsSVCC Intro to Grails
SVCC Intro to Grails
James Williams
 
Introduction to WebGL and Three.js
Introduction to WebGL and Three.jsIntroduction to WebGL and Three.js
Introduction to WebGL and Three.js
James Williams
 
Intro to HTML5 Game Programming
Intro to HTML5 Game ProgrammingIntro to HTML5 Game Programming
Intro to HTML5 Game Programming
James 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 Apps
James Williams
 
Introduction to Griffon
Introduction to GriffonIntroduction to Griffon
Introduction to Griffon
James Williams
 
Griffon for the Enterprise
Griffon for the EnterpriseGriffon for the Enterprise
Griffon for the Enterprise
James Williams
 
Game programming with Groovy
Game programming with GroovyGame programming with Groovy
Game programming with Groovy
James Williams
 
Porting legacy apps to Griffon
Porting legacy apps to GriffonPorting legacy apps to Griffon
Porting legacy apps to Griffon
James Williams
 
Creating Voice Powered Apps with Ribbit
Creating Voice Powered Apps with RibbitCreating Voice Powered Apps with Ribbit
Creating Voice Powered Apps with Ribbit
James Williams
 
Griffon: Swing just got fun again
Griffon: Swing just got fun againGriffon: Swing just got fun again
Griffon: Swing just got fun again
James Williams
 
Griffon: Swing just got fun again
Griffon: Swing just got fun againGriffon: 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 ApplicationsExtending 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 GroovyBoosting Your Testing Productivity with Groovy
Boosting Your Testing Productivity with Groovy
James Williams
 
Griffon: Re-imaging Desktop Java Technology
Griffon: Re-imaging Desktop Java TechnologyGriffon: Re-imaging Desktop Java Technology
Griffon: Re-imaging Desktop Java Technology
James Williams
 

Recently uploaded (20)

Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
Datastucture-Unit 4-Linked List Presentation.pptx
Datastucture-Unit 4-Linked List Presentation.pptxDatastucture-Unit 4-Linked List Presentation.pptx
Datastucture-Unit 4-Linked List Presentation.pptx
kaleeswaric3
 
Learn the Basics of Agile Development: Your Step-by-Step Guide
Learn the Basics of Agile Development: Your Step-by-Step GuideLearn the Basics of Agile Development: Your Step-by-Step Guide
Learn the Basics of Agile Development: Your Step-by-Step Guide
Marcel David
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
"Client Partnership — the Path to Exponential Growth for Companies Sized 50-5...
"Client Partnership — the Path to Exponential Growth for Companies Sized 50-5..."Client Partnership — the Path to Exponential Growth for Companies Sized 50-5...
"Client Partnership — the Path to Exponential Growth for Companies Sized 50-5...
Fwdays
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
Automation Dreamin': Capture User Feedback From Anywhere
Automation Dreamin': Capture User Feedback From AnywhereAutomation Dreamin': Capture User Feedback From Anywhere
Automation Dreamin': Capture User Feedback From Anywhere
Lynda Kane
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
Buckeye Dreamin' 2023: De-fogging Debug Logs
Buckeye Dreamin' 2023: De-fogging Debug LogsBuckeye Dreamin' 2023: De-fogging Debug Logs
Buckeye Dreamin' 2023: De-fogging Debug Logs
Lynda Kane
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Rock, Paper, Scissors: An Apex Map Learning Journey
Rock, Paper, Scissors: An Apex Map Learning JourneyRock, Paper, Scissors: An Apex Map Learning Journey
Rock, Paper, Scissors: An Apex Map Learning Journey
Lynda Kane
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
Automation Dreamin' 2022: Sharing Some Gratitude with Your Users
Automation Dreamin' 2022: Sharing Some Gratitude with Your UsersAutomation Dreamin' 2022: Sharing Some Gratitude with Your Users
Automation Dreamin' 2022: Sharing Some Gratitude with Your Users
Lynda Kane
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
Datastucture-Unit 4-Linked List Presentation.pptx
Datastucture-Unit 4-Linked List Presentation.pptxDatastucture-Unit 4-Linked List Presentation.pptx
Datastucture-Unit 4-Linked List Presentation.pptx
kaleeswaric3
 
Learn the Basics of Agile Development: Your Step-by-Step Guide
Learn the Basics of Agile Development: Your Step-by-Step GuideLearn the Basics of Agile Development: Your Step-by-Step Guide
Learn the Basics of Agile Development: Your Step-by-Step Guide
Marcel David
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
"Client Partnership — the Path to Exponential Growth for Companies Sized 50-5...
"Client Partnership — the Path to Exponential Growth for Companies Sized 50-5..."Client Partnership — the Path to Exponential Growth for Companies Sized 50-5...
"Client Partnership — the Path to Exponential Growth for Companies Sized 50-5...
Fwdays
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
Automation Dreamin': Capture User Feedback From Anywhere
Automation Dreamin': Capture User Feedback From AnywhereAutomation Dreamin': Capture User Feedback From Anywhere
Automation Dreamin': Capture User Feedback From Anywhere
Lynda Kane
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
Buckeye Dreamin' 2023: De-fogging Debug Logs
Buckeye Dreamin' 2023: De-fogging Debug LogsBuckeye Dreamin' 2023: De-fogging Debug Logs
Buckeye Dreamin' 2023: De-fogging Debug Logs
Lynda Kane
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Rock, Paper, Scissors: An Apex Map Learning Journey
Rock, Paper, Scissors: An Apex Map Learning JourneyRock, Paper, Scissors: An Apex Map Learning Journey
Rock, Paper, Scissors: An Apex Map Learning Journey
Lynda Kane
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
Automation Dreamin' 2022: Sharing Some Gratitude with Your Users
Automation Dreamin' 2022: Sharing Some Gratitude with Your UsersAutomation Dreamin' 2022: Sharing Some Gratitude with Your Users
Automation Dreamin' 2022: Sharing Some Gratitude with Your Users
Lynda Kane
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 

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