SlideShare a Scribd company logo
MongoDB + Java - Everything you need to know
MongoDB + Java
Everything you need to know
Agenda
• MongoDB + Java
• Driver
• ODM's
• JVM Languages
• Hadoop
Ola, I'm Norberto!
Norberto Leite
Technical Evangelist
Madrid, Spain
@nleite
norberto@mongodb.com
http://www.mongodb.com/norberto
A few announcements…
Announcements
Announcements
• Java 3.0.0-beta2 available for testing
– Generic MongoCollection
– New Codec infrastructure
– Asynchronous Support
– New core driver
• Better support for JVM languages
– https://github.com/mongodb/mongo-java-
driver/releases/tag/r3.0.0-beta2
• RX Streams – testing only!
– https://github.com/rozza/mongo-java-driver-
reactivestreams
http://www.humanandnatural.com/data/media/178/badan_jaran_desert_oasis_china.jpg
Let's go and test this!
http://www.tinypm.com/blog/wp-content/uploads/2015/01/hammer.jpg
Java Driver
Getting Started
• Review our documentation
– http://docs.mongodb.org/ecosystem/drivers/java/
Connecting
http://std3.ru/d3/09/1379154681-d309dacac47a71fb92480157f1d9a0ea.jpg
Connecting
public void connect() throws UnknownHostException{
String host = "mongodb://localhost:27017";
//connect to host
MongoClient mongoClient = new MongoClient(host);
…
}
Connecting
public void connect() throws UnknownHostException{
String host = "mongodb://localhost:27017";
//connect to host
MongoClient mongoClient = new MongoClient(host);
…
}
Client Instance
Host Machine
Connecting
public void connectServerAddress() throws UnknownHostException{
String host = "mongodb://localhost:27017";
//using ServerAddress
ServerAddress serverAddress = new ServerAddress(host);
//connect to host
MongoClient mongoClient = new MongoClient(serverAddress);
…
}
Connecting
public void connectServerAddress() throws UnknownHostException{
String host = "mongodb://localhost:27017";
//using ServerAddress
ServerAddress serverAddress = new ServerAddress(host);
//connect to host
MongoClient mongoClient = new MongoClient(serverAddress);
…
}
Server Address Instance
Connecting
public boolean connectReplicas() throws UnknownHostException{
//replica set members
String []hosts = {
"mongodb://localhost:30000",
"mongodb://localhost:30001",
"mongodb://localhost:30000",
};
//list of ServerAdress
List<ServerAddress> seeds = new ArrayList<ServerAddress>();
for (String h: hosts){
seeds.add(new ServerAddress(h));
}
//connect to host
MongoClient mongoClient = new MongoClient(seeds);
…
}
Connecting
public boolean connectReplicas() throws UnknownHostException{
//replica set members
String []hosts = {
"mongodb://localhost:30000",
"mongodb://localhost:30001",
"mongodb://localhost:30000",
};
//list of ServerAdress
List<ServerAddress> seeds = new ArrayList<ServerAddress>();
for (String h: hosts){
seeds.add(new ServerAddress(h));
}
//connect to host
MongoClient mongoClient = new MongoClient(seeds);
…
}
Seed List
Database & Collections
public void connectDatabase(final String dbname, final String collname){
//database instance
DB database = mongoClient.getDB(dbname);
//collection instance
DBCollection collection = database.getCollection(collname);
https://api.mongodb.org/java/current/com/mongodb/DB.html
https://api.mongodb.org/java/current/com/mongodb/DBCollection.html
Security
public void connectServerAddress() throws UnknownHostException{
String host = "localhost:27017";
ServerAddress serverAddress = new ServerAddress(host);
String dbname = "test";
String userName = "norberto";
char[] password = {'a', 'b', 'c'};
MongoCredential credential = MongoCredential
.createMongoCRCredential(userName, dbname, password);
MongoClient mongoClient = new MongoClient(serverAddress,
Arrays.asList(credential));
http://docs.mongodb.org/ecosystem/tutorial/getting-started-with-java-
driver/#authentication-optional
Writing
http://std3.ru/d3/09/1379154681-d309dacac47a71fb92480157f1d9a0ea.jpg
Inserting
public boolean insertObject(SimplePojo p){
//lets insert on database `test`
String dbname = "test";
//on collection `simple`
String collname = "simple";
DBCollection collection = mc.getDB(dbname).getCollection(collname);
DBObject document = new BasicDBObject();
document.put("name", p.getName());
document.put("age", p.getAge());
document.put("address", p.getAddress());
//db.simple.insert( { "name": XYZ, "age": 45, "address": "49 Rue de Rivoli, 75001
Paris"})
collection.insert(document);…
}
Inserting
public boolean insertObject(SimplePojo p){
//lets insert on database `test`
String dbname = "test";
//on collection `simple`
String collname = "simple";
DBCollection collection = mc.getDB(dbname).getCollection(collname);
DBObject document = new BasicDBObject();
document.put("name", p.getName());
document.put("age", p.getAge());
document.put("address", p.getAddress());
//db.simple.insert( { "name": XYZ, "age": 45, "address": "49 Rue de Rivoli, 75001 Paris"})
collection.insert(document);
…
}
Collection instance
BSON wrapper
Inserting
public boolean insertObject(SimplePojo p){
…
WriteResult result = collection.insert(document);
//log number of inserted documents
log.debug("Number of inserted results " + result.getN() );
…
}
https://api.mongodb.org/java/current/com/mongodb/DBObject.html
https://api.mongodb.org/java/current/com/mongodb/WriteResult.html
Update
public long savePojo(SimplePojo p) {
DBObject document = BasicDBObjectBuilder.start()
.add("name", p.getName())
.add("age", p.getAge())
.add("address", p.getAddress()).get();
//method replaces the existing database document by this new one
WriteResult res = this.collection.save(document);
//if it does not exist will create one (upsert)
return res.getN();
}
Update
public long savePojo(SimplePojo p) {
DBObject document = BasicDBObjectBuilder.start()
.add("name", p.getName())
.add("age", p.getAge())
.add("address", p.getAddress()).get();
//method replaces the existing database document by this new one
WriteResult res = this.collection.save(document);
//if it does not exist creates one (upsert)
return res.getN();
}
Save method
Update
public long updateAddress( SimplePojo p, Address a ){
//{ 'name': XYZ}
DBObject query = QueryBuilder.start("name").is(p.getName()).get();
DBObject address = BasicDBObjectBuilder.start()
.add("street", a.getStreet())
.add("city", a.getCity())
.add("number", a.getNumber())
.add("district", a.getDistrict()).get();
DBObject update = BasicDBObjectBuilder.start().add("name",
p.getName()).add("age", p.getAge()).add("address", address).get();
return this.collection.update(query, update).getN();
}
Update
public long updateAddress( SimplePojo p, Address a ){
//{ 'name': XYZ}
DBObject query = QueryBuilder.start("name").is(p.getName()).get();
DBObject address = BasicDBObjectBuilder.start()
.add("street", a.getStreet())
.add("city", a.getCity())
.add("number", a.getNumber())
.add("district", a.getDistrict()).get();
DBObject update = BasicDBObjectBuilder.start().add("name",
p.getName()).add("age", p.getAge()).add("address", address).get();
return this.collection.update(query, update).getN();
}
Query Object
Update Object
Update
public long updateSetAddress( SimplePojo p, Address a ){
//{ 'name': XYZ}
DBObject query = QueryBuilder.start("name").is(p.getName()).get();
DBObject address = BasicDBObjectBuilder.start()
.add("street", a.getStreet())
.add("city", a.getCity())
.add("number", a.getNumber())
.add("district", a.getDistrict()).get();
//db.simple.update( {"name": XYZ}, {"$set":{ "address": ...} } )
DBObject update = BasicDBObjectBuilder.start()
.append("$set", new BasicDBObject("address", address) ).get();
return this.collection.update(query, update).getN();
}
Update
public long updateSetAddress( SimplePojo p, Address a ){
//{ 'name': XYZ}
DBObject query = QueryBuilder.start("name").is(p.getName()).get();
DBObject address = BasicDBObjectBuilder.start()
.add("street", a.getStreet())
.add("city", a.getCity())
.add("number", a.getNumber())
.add("district", a.getDistrict()).get();
//db.simple.update( {"name": XYZ}, {"$set":{ "address": ...} } )
DBObject update = BasicDBObjectBuilder.start()
.append("$set", new BasicDBObject("address", address) ).get();
return this.collection.update(query, update).getN();
}
Using $set operator
http://docs.mongodb.org/manual/reference/operator/update/
Remove
public long removePojo( SimplePojo p){
//query object to match documents to be removed
DBObject query = BasicDBObjectBuilder.start().add("name", p.getName()).get();
return this.collection.remove(query).getN();
}
Remove
public long removePojo( SimplePojo p){
//query object to match documents to be removed
DBObject query = BasicDBObjectBuilder.start()
.add("name", p.getName()).get();
return this.collection.remove(query).getN();
}
Matching query
Remove All
public long removeAll( ){
//empty object removes all documents > db.simple.remove({})
return this.collection.remove(new BasicDBObject()).getN();
}
Empty document
http://docs.mongodb.org/manual/reference/method/db.collection.remove/
WriteConcern
http://std3.ru/d3/09/1379154681-d309dacac47a71fb92480157f1d9a0ea.jpghttp://www.theworldeffect.com/images/6a00e54fa8abf78833011570eedcf1970b-800wi.jpg
WriteConcern
//Default
WriteConcern w1 = WriteConcern.ACKNOWLEDGED;
WriteConcern w0 = WriteConcern.UNACKNOWLEDGED;
WriteConcern j1 = WriteConcern.JOURNALED;
WriteConcern wx = WriteConcern.REPLICA_ACKNOWLEDGED;
WriteConcern majority = WriteConcern.MAJORITY;
https://api.mongodb.org/java/current/com/mongodb/WriteConcern.html
WriteConcern.ACKNOWLEDGED
WriteConcern.UNACKNOWLEDGED
WriteConcern.JOURNALED
WriteConcern.REPLICA_ACKNOWLEDGED
WriteConcern
public boolean insertObjectWriteConcern(SimplePojo p){
…
WriteResult result = collection.insert(document,
WriteConcern.REPLICA_ACKNOWLEDGED);
//log number of inserted documents
log.debug("Number of inserted results " + result.getN() );
//log the last write concern used
log.info( "Last write concern used "+ result.getLastConcern() );…
}
WriteConcern
public boolean insertObjectWriteConcern(SimplePojo p){
…
WriteResult result = collection.insert(document,
WriteConcern.REPLICA_ACKNOWLEDGED);
//log number of inserted documents
log.debug("Number of inserted results " + result.getN() );
//log the last write concern used
log.info( "Last write concern used "+ result.getLastConcern() );
…
}
Confirm on Replicas
WriteConcern
public void setWriteConcernLevels(WriteConcern wc){
//connection level
this.mc.setWriteConcern(wc);
//database level
this.mc.getDB("test").setWriteConcern(wc);
//collection level
this.mc.getDB("test").getCollection("simple").setWriteConcern(wc);
//instruction level
this.mc.getDB("test").getCollection("simple").insert( new BasicDBObject() ,
wc);
}
Bulk Write
http://images.fineartamerica.com/images-medium-large/2-my-old-bucket-curt-simpson.jpg
Write Bulk
public boolean bulkInsert(List<SimplePojo> ps){
…
//initialize a bulk write operation
BulkWriteOperation bulkOp = coll.initializeUnorderedBulkOperation();
for (SimplePojo p : ps){
DBObject document = BasicDBObjectBuilder.start()
.add("name", p.getName())
.add("age", p.getAge())
.add("address", p.getAddress()).get();
bulkOp.insert(document);
}
//call the set of inserts
bulkOp.execute();
…
}
Inserting Bulk
public void writeSeveral( SimplePojo p, ComplexPojo c){
//initialize ordered bulk
BulkWriteOperation bulk = this.collection.initializeOrderedBulkOperation();
DBObject q1 = BasicDBObjectBuilder.start()
.add("name", p.getName()).get();
//remove the previous document
bulk.find(q1).removeOne();
//insert the new document
bulk.insert( c.encodeDBObject() );
BulkWriteResult result = bulk.execute();
//do something with the result
result.getClass();
}
Reading
http://std3.ru/d3/09/1379154681-d309dacac47a71fb92480157f1d9a0ea.jpghttp://1.bp.blogspot.com/_uYSlZ_2-VwI/SK0TrNUBVBI/AAAAAAAAASs/5334Tlv0IIY/s1600-h/lady_reading_book.jpg
Read
public SimplePojo get(){
//basic findOne operation
DBObject doc = this.collection.findOne();
SimplePojo pojo = new SimplePojo();
//casting to destination type
pojo.setAddress((String) doc.get("address"));
pojo.setAge( (int) doc.get("age") );
pojo.setAddress( (String) doc.get("address") );
return pojo;
}
Read
public List<SimplePojo> getSeveral(){
List<SimplePojo> pojos = new ArrayList<SimplePojo>();
//returns a cursor
DBCursor cursor = this.collection.find();
//iterates over the cursor
for (DBObject document : cursor){
//calls factory or transformation method
pojos.add( this.transform(document) );
}
return pojos;
}
Read
public List<SimplePojo> getSeveral(){
List<SimplePojo> pojos = new ArrayList<SimplePojo>();
//returns a cursor
DBCursor cursor = this.collection.find();
//iterates over the cursor
for (DBObject document : cursor){
//calls factory or transformation method
pojos.add( this.transform(document) );
}
return pojos;
}
Returns Cursor
Read
public List<SimplePojo> getAtAge(int age) {
List<SimplePojo> pojos = new ArrayList<SimplePojo>();
DBObject criteria = new BasicDBObject("age", age);
// matching operator { "age": age}
DBCursor cursor = this.collection.find(criteria);
// iterates over the cursor
for (DBObject document : cursor) {
// calls factory or transformation method
pojos.add(this.transform(document));
}
return pojos;
}
Matching operator
Read
public List<SimplePojo> getOlderThan( int minAge){
…
DBObject criteria = new BasicDBObject( "$gt",
new BasicDBObject("age", minAge));
// matching operator { "$gt": { "age": minAge} }
DBCursor cursor = this.collection.find(criteria);
…
}
Read
public List<SimplePojo> getOlderThan( int minAge){
…
DBObject criteria = new BasicDBObject( "$gt",
new BasicDBObject("age", minAge));
// matching operator { "$gt": { "age": minAge} }
DBCursor cursor = this.collection.find(criteria);
…
}
Range operator
http://docs.mongodb.org/manual/reference/operator/query/
Read & Filtering
public String getAddress(final String name) {
DBObject criteria = new BasicDBObject("name", name);
//we want the address field
DBObject fields = new BasicDBObject( "address", 1 );
//and exclude _id too
fields.put("_id", 0);
// db.simple.find( { "name": name}, {"_id:0", "address":1} )
DBObject document = this.collection.findOne(criteria, fields);
//we can check if this is a partial document
document.isPartialObject();
return (String) document.get("address");
}
Read & Filtering
public String getAddress(final String name) {
DBObject criteria = new BasicDBObject("name", name);
//we want the address field
DBObject fields = new BasicDBObject( "address", 1 );
//and exclude _id too
fields.put("_id", 0);
// db.simple.find( { "name": name}, {"_id:0", "address":1} )
DBObject document = this.collection.findOne(criteria, fields);
//we can check if this is a partial document
document.isPartialObject();
return (String) document.get("address");
}
Select fields
Read Preference
http://2.bp.blogspot.com/-CW3UtTpWoqg/UHhJ0gzjxcI/AAAAAAAAQz0/l_ozSnrwkvo/s1600/Grigori+Semenovich+Sedov+-+Choosing+the+bride+of+Czar+Alexis.jpg
Read Preference
//default
ReadPreference.primary();
ReadPreference.primaryPreferred();
ReadPreference.secondary();
ReadPreference.secondaryPreferred();
ReadPreference.nearest();
https://api.mongodb.org/java/current/com/mongodb/ReadPreference.html
Read Preference – Tag Aware
//read from specific tag
DBObject tag = new BasicDBObject( "datacenter", "Porto" );
ReadPreference readPref = ReadPreference.secondary(tag);
http://docs.mongodb.org/manual/tutorial/configure-replica-set-tag-sets/
Read Preference
public String getName( final int age ){
DBObject criteria = new BasicDBObject("age", age);
DBObject fields = new BasicDBObject( "name", 1 );
//set to read from nearest node
DBObject document = this.collection.findOne(criteria, fields,
ReadPreference.nearest() );
//return the element
return (String) document.get("name");
}
Read Preference
Aggregation
// create our pipeline operations, first with the $match
DBObject match = new BasicDBObject("$match", new
BasicDBObject("type", "airfare"));
// build the $projection operation
DBObject fields = new BasicDBObject("department", 1);
fields.put("amount", 1);
fields.put("_id", 0);
DBObject project = new BasicDBObject("$project", fields );
// Now the $group operation
DBObject groupFields = new BasicDBObject( "_id", "$department");
groupFields.put("average", new BasicDBObject( "$avg", "$amount"));
DBObject group = new BasicDBObject("$group", groupFields);
…
Aggregation
// Finally the $sort operation
DBObject sort = new BasicDBObject("$sort", new BasicDBObject("amount",
-1));
// run aggregation
List<DBObject> pipeline = Arrays.asList(match, project, group, sort);
AggregationOutput output = coll.aggregate(pipeline);
Java ODM's
Morphia
Morphia
Morphia
public class Employee {
// auto-generated, if not set (see ObjectId)
@Id ObjectId id;
// value types are automatically persisted
String firstName, lastName;
// only non-null values are stored
Long salary = null;
// by default fields are @Embedded
Address address;
…
}
Morphia
public class Employee {
…
//references can be saved without automatic loading
Key<Employee> manager;
//refs are stored**, and loaded automatically
@Reference List<Employee> underlings = new ArrayList<Employee>();
// stored in one binary field
@Serialized EncryptedReviews encryptedReviews;
//fields can be renamed
@Property("started") Date startDate;
@Property("left") Date endDate;
…
}
SpringData
Spring Data
http://projects.spring.io/spring-data-mongodb/
Jongo
Jongo
http://jongo.org/
Others
• DataNucleus JPA/JDO
• lib-mongomapper
• Kundera
• Hibernate OGM
JVM Languages
Scala
• http://docs.mongodb.org/ecosystem/drivers/scala/
• Cashbah
– Java Driver Wrapper
– Idiomatic Scala Interface for MongoDB
• Community
– Hammersmith
– Salat
– Reactive Mongo
– Lift Web Framework
– BlueEyes
– MSSD
Clojure
http://clojuremongodb.info/
Groovy
https://github.com/poiati/gmongo
Hadoop
MongoDB Hadoop Connector
• MongoDB and BSON
– Input and Output formats
• Computes splits to read data
• Support for
– Filtering data with MongoDB queries
– Authentication (and separate for configdb)
– Reading from shard Primary directly
– ReadPreferences and Replica Set tags (via MongoDB URI)
– Appending to existing collections (MapReduce, Pig, Spark)
For More Information
Resource Location
Case Studies mongodb.com/customers
Presentations mongodb.com/presentations
Free Online Training education.mongodb.com
Webinars and Events mongodb.com/events
Documentation docs.mongodb.org
MongoDB Downloads mongodb.com/download
Additional Info info@mongodb.com
http://cl.jroo.me/z3/v/D/C/e/a.baa-Too-many-bicycles-on-the-van.jpg
Questions?
@nleite
norberto@mongodb.com
http://www.mongodb.com/norberto
MongoDB + Java - Everything you need to know

More Related Content

PDF
Java development with MongoDB
PPTX
Morphia: Simplifying Persistence for Java and MongoDB
PDF
Java Persistence Frameworks for MongoDB
PPTX
Java Development with MongoDB
PPTX
MongoDB + Java + Spring Data
PPTX
Simplifying Persistence for Java and MongoDB with Morphia
PPTX
MongoDB: Easy Java Persistence with Morphia
PPTX
Java Persistence Frameworks for MongoDB
Java development with MongoDB
Morphia: Simplifying Persistence for Java and MongoDB
Java Persistence Frameworks for MongoDB
Java Development with MongoDB
MongoDB + Java + Spring Data
Simplifying Persistence for Java and MongoDB with Morphia
MongoDB: Easy Java Persistence with Morphia
Java Persistence Frameworks for MongoDB

What's hot (18)

PPTX
Morphia, Spring Data & Co.
PDF
Webinar: MongoDB Persistence with Java and Morphia
PDF
MongoDB Performance Tuning
PDF
Webinar: Building Your First App with MongoDB and Java
PPTX
Spring Data, Jongo & Co.
PPTX
Getting Started with MongoDB and NodeJS
PPTX
Back to Basics Webinar 5: Introduction to the Aggregation Framework
PPS
MongoDB crud
PPTX
Benefits of Using MongoDB Over RDBMS (At An Evening with MongoDB Minneapolis ...
PDF
MongoDB World 2016: Deciphering .explain() Output
PDF
Map/Confused? A practical approach to Map/Reduce with MongoDB
PPTX
Mythbusting: Understanding How We Measure the Performance of MongoDB
PDF
What do you mean, Backwards Compatibility?
PDF
NoSQL and JavaScript: a Love Story
ODP
DrupalCon Chicago Practical MongoDB and Drupal
PDF
Indexing and Query Optimizer (Mongo Austin)
PDF
Building Apps with MongoDB
PDF
MongoDB Performance Tuning
Morphia, Spring Data & Co.
Webinar: MongoDB Persistence with Java and Morphia
MongoDB Performance Tuning
Webinar: Building Your First App with MongoDB and Java
Spring Data, Jongo & Co.
Getting Started with MongoDB and NodeJS
Back to Basics Webinar 5: Introduction to the Aggregation Framework
MongoDB crud
Benefits of Using MongoDB Over RDBMS (At An Evening with MongoDB Minneapolis ...
MongoDB World 2016: Deciphering .explain() Output
Map/Confused? A practical approach to Map/Reduce with MongoDB
Mythbusting: Understanding How We Measure the Performance of MongoDB
What do you mean, Backwards Compatibility?
NoSQL and JavaScript: a Love Story
DrupalCon Chicago Practical MongoDB and Drupal
Indexing and Query Optimizer (Mongo Austin)
Building Apps with MongoDB
MongoDB Performance Tuning
Ad

Viewers also liked (17)

PPTX
Building Spring Data with MongoDB
PPT
WebEngage demo at Unpluggd (Nov, 2011)
KEY
The Spring Data MongoDB Project
PDF
PHP client - Mongo db User Group Pune
PDF
Spring Data MongoDB 介紹
PDF
MongoDB training for java software engineers
PDF
Build an AngularJS, Java, MongoDB Web App in an hour
PDF
Mongo DB on the JVM - Brendan McAdams
PDF
Migrating from RDBMS to MongoDB
PDF
AngularJS performance & production tips
PPSX
Génie Logiciel : les tests
PDF
How to monitor MongoDB
PPTX
The Aggregation Framework
PDF
ng-owasp: OWASP Top 10 for AngularJS Applications
PDF
Tests & recette - Les fondamentaux
ODP
Présentation Agile Testing
Building Spring Data with MongoDB
WebEngage demo at Unpluggd (Nov, 2011)
The Spring Data MongoDB Project
PHP client - Mongo db User Group Pune
Spring Data MongoDB 介紹
MongoDB training for java software engineers
Build an AngularJS, Java, MongoDB Web App in an hour
Mongo DB on the JVM - Brendan McAdams
Migrating from RDBMS to MongoDB
AngularJS performance & production tips
Génie Logiciel : les tests
How to monitor MongoDB
The Aggregation Framework
ng-owasp: OWASP Top 10 for AngularJS Applications
Tests & recette - Les fondamentaux
Présentation Agile Testing
Ad

Similar to MongoDB + Java - Everything you need to know (20)

PPTX
Dev Jumpstart: Build Your First App with MongoDB
KEY
CouchDB on Android
PDF
How to Write Node.js Module
PPTX
Conceptos básicos. Seminario web 2: Su primera aplicación MongoDB
PPT
Micro-ORM Introduction - Don't overcomplicate
PDF
Utilizing Powerful Extensions for Analytics and Operations
PDF
Neo4j GraphTour: Utilizing Powerful Extensions for Analytics and Operations
KEY
[Coscup 2012] JavascriptMVC
PPT
Play!ng with scala
PDF
GraphTour - Utilizing Powerful Extensions for Analytics & Operations
PDF
Projeto-web-services-Spring-Boot-JPA.pdf
PPTX
Full stack development with node and NoSQL - All Things Open - October 2017
PPTX
Full Stack Development with Node.js and NoSQL
ODP
This upload requires better support for ODP format
PDF
CouchDB Mobile - From Couch to 5K in 1 Hour
PPTX
Back to Basics, webinar 2: La tua prima applicazione MongoDB
PPTX
Webinar: What's new in the .NET Driver
PDF
Utilizing Powerful Extensions for Analytics and Operations
PDF
My way to clean android - Android day salamanca edition
PPT
nodejs tutorial foor free download from academia
Dev Jumpstart: Build Your First App with MongoDB
CouchDB on Android
How to Write Node.js Module
Conceptos básicos. Seminario web 2: Su primera aplicación MongoDB
Micro-ORM Introduction - Don't overcomplicate
Utilizing Powerful Extensions for Analytics and Operations
Neo4j GraphTour: Utilizing Powerful Extensions for Analytics and Operations
[Coscup 2012] JavascriptMVC
Play!ng with scala
GraphTour - Utilizing Powerful Extensions for Analytics & Operations
Projeto-web-services-Spring-Boot-JPA.pdf
Full stack development with node and NoSQL - All Things Open - October 2017
Full Stack Development with Node.js and NoSQL
This upload requires better support for ODP format
CouchDB Mobile - From Couch to 5K in 1 Hour
Back to Basics, webinar 2: La tua prima applicazione MongoDB
Webinar: What's new in the .NET Driver
Utilizing Powerful Extensions for Analytics and Operations
My way to clean android - Android day salamanca edition
nodejs tutorial foor free download from academia

More from Norberto Leite (20)

PDF
Data Modelling for MongoDB - MongoDB.local Tel Aviv
PPTX
Avoid Query Pitfalls
PPTX
MongoDB and Spark
PDF
Mongo db 3.4 Overview
PDF
MongoDB Certification Study Group - May 2016
PDF
Geospatial and MongoDB
PDF
MongodB Internals
PDF
MongoDB WiredTiger Internals
PDF
MongoDB 3.2 Feature Preview
PDF
Mongodb Spring
PDF
MongoDB on Azure
PDF
MongoDB: Agile Combustion Engine
PDF
MongoDB Capacity Planning
PDF
Spark and MongoDB
PDF
Analyse Yourself
PDF
Python and MongoDB
PDF
Strongly Typed Languages and Flexible Schemas
PDF
Effectively Deploying MongoDB on AEM
PPTX
Advanced applications with MongoDB
PDF
MongoDB and Node.js
Data Modelling for MongoDB - MongoDB.local Tel Aviv
Avoid Query Pitfalls
MongoDB and Spark
Mongo db 3.4 Overview
MongoDB Certification Study Group - May 2016
Geospatial and MongoDB
MongodB Internals
MongoDB WiredTiger Internals
MongoDB 3.2 Feature Preview
Mongodb Spring
MongoDB on Azure
MongoDB: Agile Combustion Engine
MongoDB Capacity Planning
Spark and MongoDB
Analyse Yourself
Python and MongoDB
Strongly Typed Languages and Flexible Schemas
Effectively Deploying MongoDB on AEM
Advanced applications with MongoDB
MongoDB and Node.js

Recently uploaded (20)

PPTX
Machine Learning_overview_presentation.pptx
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
A comparative analysis of optical character recognition models for extracting...
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PPT
Teaching material agriculture food technology
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Getting Started with Data Integration: FME Form 101
PDF
Encapsulation theory and applications.pdf
PDF
cuic standard and advanced reporting.pdf
PPTX
SOPHOS-XG Firewall Administrator PPT.pptx
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
PPTX
Group 1 Presentation -Planning and Decision Making .pptx
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
Machine Learning_overview_presentation.pptx
Programs and apps: productivity, graphics, security and other tools
A comparative analysis of optical character recognition models for extracting...
Digital-Transformation-Roadmap-for-Companies.pptx
Spectral efficient network and resource selection model in 5G networks
The Rise and Fall of 3GPP – Time for a Sabbatical?
Teaching material agriculture food technology
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Network Security Unit 5.pdf for BCA BBA.
Getting Started with Data Integration: FME Form 101
Encapsulation theory and applications.pdf
cuic standard and advanced reporting.pdf
SOPHOS-XG Firewall Administrator PPT.pptx
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Per capita expenditure prediction using model stacking based on satellite ima...
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
Group 1 Presentation -Planning and Decision Making .pptx
MYSQL Presentation for SQL database connectivity
Diabetes mellitus diagnosis method based random forest with bat algorithm

MongoDB + Java - Everything you need to know

  • 2. MongoDB + Java Everything you need to know
  • 3. Agenda • MongoDB + Java • Driver • ODM's • JVM Languages • Hadoop
  • 4. Ola, I'm Norberto! Norberto Leite Technical Evangelist Madrid, Spain @nleite [email protected] http://www.mongodb.com/norberto
  • 7. Announcements • Java 3.0.0-beta2 available for testing – Generic MongoCollection – New Codec infrastructure – Asynchronous Support – New core driver • Better support for JVM languages – https://github.com/mongodb/mongo-java- driver/releases/tag/r3.0.0-beta2 • RX Streams – testing only! – https://github.com/rozza/mongo-java-driver- reactivestreams
  • 8. http://www.humanandnatural.com/data/media/178/badan_jaran_desert_oasis_china.jpg Let's go and test this! http://www.tinypm.com/blog/wp-content/uploads/2015/01/hammer.jpg
  • 10. Getting Started • Review our documentation – http://docs.mongodb.org/ecosystem/drivers/java/
  • 12. Connecting public void connect() throws UnknownHostException{ String host = "mongodb://localhost:27017"; //connect to host MongoClient mongoClient = new MongoClient(host); … }
  • 13. Connecting public void connect() throws UnknownHostException{ String host = "mongodb://localhost:27017"; //connect to host MongoClient mongoClient = new MongoClient(host); … } Client Instance Host Machine
  • 14. Connecting public void connectServerAddress() throws UnknownHostException{ String host = "mongodb://localhost:27017"; //using ServerAddress ServerAddress serverAddress = new ServerAddress(host); //connect to host MongoClient mongoClient = new MongoClient(serverAddress); … }
  • 15. Connecting public void connectServerAddress() throws UnknownHostException{ String host = "mongodb://localhost:27017"; //using ServerAddress ServerAddress serverAddress = new ServerAddress(host); //connect to host MongoClient mongoClient = new MongoClient(serverAddress); … } Server Address Instance
  • 16. Connecting public boolean connectReplicas() throws UnknownHostException{ //replica set members String []hosts = { "mongodb://localhost:30000", "mongodb://localhost:30001", "mongodb://localhost:30000", }; //list of ServerAdress List<ServerAddress> seeds = new ArrayList<ServerAddress>(); for (String h: hosts){ seeds.add(new ServerAddress(h)); } //connect to host MongoClient mongoClient = new MongoClient(seeds); … }
  • 17. Connecting public boolean connectReplicas() throws UnknownHostException{ //replica set members String []hosts = { "mongodb://localhost:30000", "mongodb://localhost:30001", "mongodb://localhost:30000", }; //list of ServerAdress List<ServerAddress> seeds = new ArrayList<ServerAddress>(); for (String h: hosts){ seeds.add(new ServerAddress(h)); } //connect to host MongoClient mongoClient = new MongoClient(seeds); … } Seed List
  • 18. Database & Collections public void connectDatabase(final String dbname, final String collname){ //database instance DB database = mongoClient.getDB(dbname); //collection instance DBCollection collection = database.getCollection(collname); https://api.mongodb.org/java/current/com/mongodb/DB.html https://api.mongodb.org/java/current/com/mongodb/DBCollection.html
  • 19. Security public void connectServerAddress() throws UnknownHostException{ String host = "localhost:27017"; ServerAddress serverAddress = new ServerAddress(host); String dbname = "test"; String userName = "norberto"; char[] password = {'a', 'b', 'c'}; MongoCredential credential = MongoCredential .createMongoCRCredential(userName, dbname, password); MongoClient mongoClient = new MongoClient(serverAddress, Arrays.asList(credential)); http://docs.mongodb.org/ecosystem/tutorial/getting-started-with-java- driver/#authentication-optional
  • 21. Inserting public boolean insertObject(SimplePojo p){ //lets insert on database `test` String dbname = "test"; //on collection `simple` String collname = "simple"; DBCollection collection = mc.getDB(dbname).getCollection(collname); DBObject document = new BasicDBObject(); document.put("name", p.getName()); document.put("age", p.getAge()); document.put("address", p.getAddress()); //db.simple.insert( { "name": XYZ, "age": 45, "address": "49 Rue de Rivoli, 75001 Paris"}) collection.insert(document);… }
  • 22. Inserting public boolean insertObject(SimplePojo p){ //lets insert on database `test` String dbname = "test"; //on collection `simple` String collname = "simple"; DBCollection collection = mc.getDB(dbname).getCollection(collname); DBObject document = new BasicDBObject(); document.put("name", p.getName()); document.put("age", p.getAge()); document.put("address", p.getAddress()); //db.simple.insert( { "name": XYZ, "age": 45, "address": "49 Rue de Rivoli, 75001 Paris"}) collection.insert(document); … } Collection instance BSON wrapper
  • 23. Inserting public boolean insertObject(SimplePojo p){ … WriteResult result = collection.insert(document); //log number of inserted documents log.debug("Number of inserted results " + result.getN() ); … } https://api.mongodb.org/java/current/com/mongodb/DBObject.html https://api.mongodb.org/java/current/com/mongodb/WriteResult.html
  • 24. Update public long savePojo(SimplePojo p) { DBObject document = BasicDBObjectBuilder.start() .add("name", p.getName()) .add("age", p.getAge()) .add("address", p.getAddress()).get(); //method replaces the existing database document by this new one WriteResult res = this.collection.save(document); //if it does not exist will create one (upsert) return res.getN(); }
  • 25. Update public long savePojo(SimplePojo p) { DBObject document = BasicDBObjectBuilder.start() .add("name", p.getName()) .add("age", p.getAge()) .add("address", p.getAddress()).get(); //method replaces the existing database document by this new one WriteResult res = this.collection.save(document); //if it does not exist creates one (upsert) return res.getN(); } Save method
  • 26. Update public long updateAddress( SimplePojo p, Address a ){ //{ 'name': XYZ} DBObject query = QueryBuilder.start("name").is(p.getName()).get(); DBObject address = BasicDBObjectBuilder.start() .add("street", a.getStreet()) .add("city", a.getCity()) .add("number", a.getNumber()) .add("district", a.getDistrict()).get(); DBObject update = BasicDBObjectBuilder.start().add("name", p.getName()).add("age", p.getAge()).add("address", address).get(); return this.collection.update(query, update).getN(); }
  • 27. Update public long updateAddress( SimplePojo p, Address a ){ //{ 'name': XYZ} DBObject query = QueryBuilder.start("name").is(p.getName()).get(); DBObject address = BasicDBObjectBuilder.start() .add("street", a.getStreet()) .add("city", a.getCity()) .add("number", a.getNumber()) .add("district", a.getDistrict()).get(); DBObject update = BasicDBObjectBuilder.start().add("name", p.getName()).add("age", p.getAge()).add("address", address).get(); return this.collection.update(query, update).getN(); } Query Object Update Object
  • 28. Update public long updateSetAddress( SimplePojo p, Address a ){ //{ 'name': XYZ} DBObject query = QueryBuilder.start("name").is(p.getName()).get(); DBObject address = BasicDBObjectBuilder.start() .add("street", a.getStreet()) .add("city", a.getCity()) .add("number", a.getNumber()) .add("district", a.getDistrict()).get(); //db.simple.update( {"name": XYZ}, {"$set":{ "address": ...} } ) DBObject update = BasicDBObjectBuilder.start() .append("$set", new BasicDBObject("address", address) ).get(); return this.collection.update(query, update).getN(); }
  • 29. Update public long updateSetAddress( SimplePojo p, Address a ){ //{ 'name': XYZ} DBObject query = QueryBuilder.start("name").is(p.getName()).get(); DBObject address = BasicDBObjectBuilder.start() .add("street", a.getStreet()) .add("city", a.getCity()) .add("number", a.getNumber()) .add("district", a.getDistrict()).get(); //db.simple.update( {"name": XYZ}, {"$set":{ "address": ...} } ) DBObject update = BasicDBObjectBuilder.start() .append("$set", new BasicDBObject("address", address) ).get(); return this.collection.update(query, update).getN(); } Using $set operator http://docs.mongodb.org/manual/reference/operator/update/
  • 30. Remove public long removePojo( SimplePojo p){ //query object to match documents to be removed DBObject query = BasicDBObjectBuilder.start().add("name", p.getName()).get(); return this.collection.remove(query).getN(); }
  • 31. Remove public long removePojo( SimplePojo p){ //query object to match documents to be removed DBObject query = BasicDBObjectBuilder.start() .add("name", p.getName()).get(); return this.collection.remove(query).getN(); } Matching query
  • 32. Remove All public long removeAll( ){ //empty object removes all documents > db.simple.remove({}) return this.collection.remove(new BasicDBObject()).getN(); } Empty document http://docs.mongodb.org/manual/reference/method/db.collection.remove/
  • 34. WriteConcern //Default WriteConcern w1 = WriteConcern.ACKNOWLEDGED; WriteConcern w0 = WriteConcern.UNACKNOWLEDGED; WriteConcern j1 = WriteConcern.JOURNALED; WriteConcern wx = WriteConcern.REPLICA_ACKNOWLEDGED; WriteConcern majority = WriteConcern.MAJORITY; https://api.mongodb.org/java/current/com/mongodb/WriteConcern.html
  • 39. WriteConcern public boolean insertObjectWriteConcern(SimplePojo p){ … WriteResult result = collection.insert(document, WriteConcern.REPLICA_ACKNOWLEDGED); //log number of inserted documents log.debug("Number of inserted results " + result.getN() ); //log the last write concern used log.info( "Last write concern used "+ result.getLastConcern() );… }
  • 40. WriteConcern public boolean insertObjectWriteConcern(SimplePojo p){ … WriteResult result = collection.insert(document, WriteConcern.REPLICA_ACKNOWLEDGED); //log number of inserted documents log.debug("Number of inserted results " + result.getN() ); //log the last write concern used log.info( "Last write concern used "+ result.getLastConcern() ); … } Confirm on Replicas
  • 41. WriteConcern public void setWriteConcernLevels(WriteConcern wc){ //connection level this.mc.setWriteConcern(wc); //database level this.mc.getDB("test").setWriteConcern(wc); //collection level this.mc.getDB("test").getCollection("simple").setWriteConcern(wc); //instruction level this.mc.getDB("test").getCollection("simple").insert( new BasicDBObject() , wc); }
  • 43. Write Bulk public boolean bulkInsert(List<SimplePojo> ps){ … //initialize a bulk write operation BulkWriteOperation bulkOp = coll.initializeUnorderedBulkOperation(); for (SimplePojo p : ps){ DBObject document = BasicDBObjectBuilder.start() .add("name", p.getName()) .add("age", p.getAge()) .add("address", p.getAddress()).get(); bulkOp.insert(document); } //call the set of inserts bulkOp.execute(); … }
  • 44. Inserting Bulk public void writeSeveral( SimplePojo p, ComplexPojo c){ //initialize ordered bulk BulkWriteOperation bulk = this.collection.initializeOrderedBulkOperation(); DBObject q1 = BasicDBObjectBuilder.start() .add("name", p.getName()).get(); //remove the previous document bulk.find(q1).removeOne(); //insert the new document bulk.insert( c.encodeDBObject() ); BulkWriteResult result = bulk.execute(); //do something with the result result.getClass(); }
  • 46. Read public SimplePojo get(){ //basic findOne operation DBObject doc = this.collection.findOne(); SimplePojo pojo = new SimplePojo(); //casting to destination type pojo.setAddress((String) doc.get("address")); pojo.setAge( (int) doc.get("age") ); pojo.setAddress( (String) doc.get("address") ); return pojo; }
  • 47. Read public List<SimplePojo> getSeveral(){ List<SimplePojo> pojos = new ArrayList<SimplePojo>(); //returns a cursor DBCursor cursor = this.collection.find(); //iterates over the cursor for (DBObject document : cursor){ //calls factory or transformation method pojos.add( this.transform(document) ); } return pojos; }
  • 48. Read public List<SimplePojo> getSeveral(){ List<SimplePojo> pojos = new ArrayList<SimplePojo>(); //returns a cursor DBCursor cursor = this.collection.find(); //iterates over the cursor for (DBObject document : cursor){ //calls factory or transformation method pojos.add( this.transform(document) ); } return pojos; } Returns Cursor
  • 49. Read public List<SimplePojo> getAtAge(int age) { List<SimplePojo> pojos = new ArrayList<SimplePojo>(); DBObject criteria = new BasicDBObject("age", age); // matching operator { "age": age} DBCursor cursor = this.collection.find(criteria); // iterates over the cursor for (DBObject document : cursor) { // calls factory or transformation method pojos.add(this.transform(document)); } return pojos; } Matching operator
  • 50. Read public List<SimplePojo> getOlderThan( int minAge){ … DBObject criteria = new BasicDBObject( "$gt", new BasicDBObject("age", minAge)); // matching operator { "$gt": { "age": minAge} } DBCursor cursor = this.collection.find(criteria); … }
  • 51. Read public List<SimplePojo> getOlderThan( int minAge){ … DBObject criteria = new BasicDBObject( "$gt", new BasicDBObject("age", minAge)); // matching operator { "$gt": { "age": minAge} } DBCursor cursor = this.collection.find(criteria); … } Range operator http://docs.mongodb.org/manual/reference/operator/query/
  • 52. Read & Filtering public String getAddress(final String name) { DBObject criteria = new BasicDBObject("name", name); //we want the address field DBObject fields = new BasicDBObject( "address", 1 ); //and exclude _id too fields.put("_id", 0); // db.simple.find( { "name": name}, {"_id:0", "address":1} ) DBObject document = this.collection.findOne(criteria, fields); //we can check if this is a partial document document.isPartialObject(); return (String) document.get("address"); }
  • 53. Read & Filtering public String getAddress(final String name) { DBObject criteria = new BasicDBObject("name", name); //we want the address field DBObject fields = new BasicDBObject( "address", 1 ); //and exclude _id too fields.put("_id", 0); // db.simple.find( { "name": name}, {"_id:0", "address":1} ) DBObject document = this.collection.findOne(criteria, fields); //we can check if this is a partial document document.isPartialObject(); return (String) document.get("address"); } Select fields
  • 56. Read Preference – Tag Aware //read from specific tag DBObject tag = new BasicDBObject( "datacenter", "Porto" ); ReadPreference readPref = ReadPreference.secondary(tag); http://docs.mongodb.org/manual/tutorial/configure-replica-set-tag-sets/
  • 57. Read Preference public String getName( final int age ){ DBObject criteria = new BasicDBObject("age", age); DBObject fields = new BasicDBObject( "name", 1 ); //set to read from nearest node DBObject document = this.collection.findOne(criteria, fields, ReadPreference.nearest() ); //return the element return (String) document.get("name"); } Read Preference
  • 58. Aggregation // create our pipeline operations, first with the $match DBObject match = new BasicDBObject("$match", new BasicDBObject("type", "airfare")); // build the $projection operation DBObject fields = new BasicDBObject("department", 1); fields.put("amount", 1); fields.put("_id", 0); DBObject project = new BasicDBObject("$project", fields ); // Now the $group operation DBObject groupFields = new BasicDBObject( "_id", "$department"); groupFields.put("average", new BasicDBObject( "$avg", "$amount")); DBObject group = new BasicDBObject("$group", groupFields); …
  • 59. Aggregation // Finally the $sort operation DBObject sort = new BasicDBObject("$sort", new BasicDBObject("amount", -1)); // run aggregation List<DBObject> pipeline = Arrays.asList(match, project, group, sort); AggregationOutput output = coll.aggregate(pipeline);
  • 63. Morphia public class Employee { // auto-generated, if not set (see ObjectId) @Id ObjectId id; // value types are automatically persisted String firstName, lastName; // only non-null values are stored Long salary = null; // by default fields are @Embedded Address address; … }
  • 64. Morphia public class Employee { … //references can be saved without automatic loading Key<Employee> manager; //refs are stored**, and loaded automatically @Reference List<Employee> underlings = new ArrayList<Employee>(); // stored in one binary field @Serialized EncryptedReviews encryptedReviews; //fields can be renamed @Property("started") Date startDate; @Property("left") Date endDate; … }
  • 67. Jongo
  • 69. Others • DataNucleus JPA/JDO • lib-mongomapper • Kundera • Hibernate OGM
  • 71. Scala • http://docs.mongodb.org/ecosystem/drivers/scala/ • Cashbah – Java Driver Wrapper – Idiomatic Scala Interface for MongoDB • Community – Hammersmith – Salat – Reactive Mongo – Lift Web Framework – BlueEyes – MSSD
  • 75. MongoDB Hadoop Connector • MongoDB and BSON – Input and Output formats • Computes splits to read data • Support for – Filtering data with MongoDB queries – Authentication (and separate for configdb) – Reading from shard Primary directly – ReadPreferences and Replica Set tags (via MongoDB URI) – Appending to existing collections (MapReduce, Pig, Spark)
  • 76. For More Information Resource Location Case Studies mongodb.com/customers Presentations mongodb.com/presentations Free Online Training education.mongodb.com Webinars and Events mongodb.com/events Documentation docs.mongodb.org MongoDB Downloads mongodb.com/download Additional Info [email protected]

Editor's Notes

  • #28: Replacing objects highly inefficient and should be avoided.