SlideShare a Scribd company logo
Mongo+java (1)
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
Mongo+java (1)

More Related Content

PPTX
MongoDB + Java - Everything you need to know
PPTX
Java Development with MongoDB
PDF
Java development with MongoDB
PDF
Java Persistence Frameworks for MongoDB
PDF
Webinar: Building Your First App with MongoDB and Java
PPTX
MongoDB + Java + Spring Data
PDF
Indexing
PPTX
MongoDB: Easy Java Persistence with Morphia
MongoDB + Java - Everything you need to know
Java Development with MongoDB
Java development with MongoDB
Java Persistence Frameworks for MongoDB
Webinar: Building Your First App with MongoDB and Java
MongoDB + Java + Spring Data
Indexing
MongoDB: Easy Java Persistence with Morphia

What's hot (20)

PDF
Building Apps with MongoDB
PPTX
Getting Started with MongoDB and NodeJS
PPTX
Back to Basics Webinar 5: Introduction to the Aggregation Framework
PPTX
Back to Basics Webinar 4: Advanced Indexing, Text and Geospatial Indexes
PPTX
Morphia, Spring Data & Co.
PPTX
Java Persistence Frameworks for MongoDB
PDF
What do you mean, Backwards Compatibility?
PPTX
Webinaire 2 de la série « Retour aux fondamentaux » : Votre première applicat...
KEY
MongoDB, PHP and the cloud - php cloud summit 2011
PDF
Hadoop - MongoDB Webinar June 2014
PPTX
Webinar: Transitioning from SQL to MongoDB
PPS
MongoDB crud
PDF
MongoDB Europe 2016 - Debugging MongoDB Performance
PDF
Storing tree structures with MongoDB
PPTX
Back to Basics: My First MongoDB Application
PDF
Map/Confused? A practical approach to Map/Reduce with MongoDB
PPTX
Benefits of Using MongoDB Over RDBMS (At An Evening with MongoDB Minneapolis ...
KEY
MongoDB Java Development - MongoBoston 2010
PDF
MongoDB World 2016: Deciphering .explain() Output
PPTX
Mongo db queries
Building Apps with MongoDB
Getting Started with MongoDB and NodeJS
Back to Basics Webinar 5: Introduction to the Aggregation Framework
Back to Basics Webinar 4: Advanced Indexing, Text and Geospatial Indexes
Morphia, Spring Data & Co.
Java Persistence Frameworks for MongoDB
What do you mean, Backwards Compatibility?
Webinaire 2 de la série « Retour aux fondamentaux » : Votre première applicat...
MongoDB, PHP and the cloud - php cloud summit 2011
Hadoop - MongoDB Webinar June 2014
Webinar: Transitioning from SQL to MongoDB
MongoDB crud
MongoDB Europe 2016 - Debugging MongoDB Performance
Storing tree structures with MongoDB
Back to Basics: My First MongoDB Application
Map/Confused? A practical approach to Map/Reduce with MongoDB
Benefits of Using MongoDB Over RDBMS (At An Evening with MongoDB Minneapolis ...
MongoDB Java Development - MongoBoston 2010
MongoDB World 2016: Deciphering .explain() Output
Mongo db queries
Ad

Viewers also liked (20)

PPTX
Back to Basics Webinar 1: Introduction to NoSQL
PPTX
MongoDB + Spring
PDF
Introduction to apache kafka
PPTX
Concurrency Control in MongoDB 3.0
PPTX
The rise of microservices - containers and orchestration
PDF
Comparing ZooKeeper and Consul
PPTX
Real-Time Distributed and Reactive Systems with Apache Kafka and Apache Accumulo
PPTX
Powering Microservices with MongoDB, Docker, Kubernetes & Kafka – MongoDB Eur...
PPTX
Hazelcast and MongoDB at Cloud CMS
PPT
HighLoad++ 2009 In-Memory Data Grids
PDF
Async Gateway или Разработка системы распределенных вычислений с нуля
PDF
Phoenix for Rubyists
PDF
50 nouvelles choses que l'on peut faire en Java 8
PDF
Алексей Николаенков, Devexperts
PDF
Hazelcast for Terracotta Users
PPTX
Code review at large scale
PDF
Amazon cloud – готовим вместе
PDF
50 new things we can do with Java 8
PDF
ЖК Зорге 9
PPTX
JFokus 50 new things with java 8
Back to Basics Webinar 1: Introduction to NoSQL
MongoDB + Spring
Introduction to apache kafka
Concurrency Control in MongoDB 3.0
The rise of microservices - containers and orchestration
Comparing ZooKeeper and Consul
Real-Time Distributed and Reactive Systems with Apache Kafka and Apache Accumulo
Powering Microservices with MongoDB, Docker, Kubernetes & Kafka – MongoDB Eur...
Hazelcast and MongoDB at Cloud CMS
HighLoad++ 2009 In-Memory Data Grids
Async Gateway или Разработка системы распределенных вычислений с нуля
Phoenix for Rubyists
50 nouvelles choses que l'on peut faire en Java 8
Алексей Николаенков, Devexperts
Hazelcast for Terracotta Users
Code review at large scale
Amazon cloud – готовим вместе
50 new things we can do with Java 8
ЖК Зорге 9
JFokus 50 new things with java 8
Ad

Similar to Mongo+java (1) (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 MongoDB (20)

PDF
MongoDB SoCal 2020: Migrate Anything* to MongoDB Atlas
PDF
MongoDB SoCal 2020: Go on a Data Safari with MongoDB Charts!
PDF
MongoDB SoCal 2020: Using MongoDB Services in Kubernetes: Any Platform, Devel...
PDF
MongoDB SoCal 2020: A Complete Methodology of Data Modeling for MongoDB
PDF
MongoDB SoCal 2020: From Pharmacist to Analyst: Leveraging MongoDB for Real-T...
PDF
MongoDB SoCal 2020: Best Practices for Working with IoT and Time-series Data
PDF
MongoDB SoCal 2020: MongoDB Atlas Jump Start
PDF
MongoDB .local San Francisco 2020: Powering the new age data demands [Infosys]
PDF
MongoDB .local San Francisco 2020: Using Client Side Encryption in MongoDB 4.2
PDF
MongoDB .local San Francisco 2020: Using MongoDB Services in Kubernetes: any ...
PDF
MongoDB .local San Francisco 2020: Go on a Data Safari with MongoDB Charts!
PDF
MongoDB .local San Francisco 2020: From SQL to NoSQL -- Changing Your Mindset
PDF
MongoDB .local San Francisco 2020: MongoDB Atlas Jumpstart
PDF
MongoDB .local San Francisco 2020: Tips and Tricks++ for Querying and Indexin...
PDF
MongoDB .local San Francisco 2020: Aggregation Pipeline Power++
PDF
MongoDB .local San Francisco 2020: A Complete Methodology of Data Modeling fo...
PDF
MongoDB .local San Francisco 2020: MongoDB Atlas Data Lake Technical Deep Dive
PDF
MongoDB .local San Francisco 2020: Developing Alexa Skills with MongoDB & Golang
PDF
MongoDB .local Paris 2020: Realm : l'ingrédient secret pour de meilleures app...
PDF
MongoDB .local Paris 2020: Upply @MongoDB : Upply : Quand le Machine Learning...
MongoDB SoCal 2020: Migrate Anything* to MongoDB Atlas
MongoDB SoCal 2020: Go on a Data Safari with MongoDB Charts!
MongoDB SoCal 2020: Using MongoDB Services in Kubernetes: Any Platform, Devel...
MongoDB SoCal 2020: A Complete Methodology of Data Modeling for MongoDB
MongoDB SoCal 2020: From Pharmacist to Analyst: Leveraging MongoDB for Real-T...
MongoDB SoCal 2020: Best Practices for Working with IoT and Time-series Data
MongoDB SoCal 2020: MongoDB Atlas Jump Start
MongoDB .local San Francisco 2020: Powering the new age data demands [Infosys]
MongoDB .local San Francisco 2020: Using Client Side Encryption in MongoDB 4.2
MongoDB .local San Francisco 2020: Using MongoDB Services in Kubernetes: any ...
MongoDB .local San Francisco 2020: Go on a Data Safari with MongoDB Charts!
MongoDB .local San Francisco 2020: From SQL to NoSQL -- Changing Your Mindset
MongoDB .local San Francisco 2020: MongoDB Atlas Jumpstart
MongoDB .local San Francisco 2020: Tips and Tricks++ for Querying and Indexin...
MongoDB .local San Francisco 2020: Aggregation Pipeline Power++
MongoDB .local San Francisco 2020: A Complete Methodology of Data Modeling fo...
MongoDB .local San Francisco 2020: MongoDB Atlas Data Lake Technical Deep Dive
MongoDB .local San Francisco 2020: Developing Alexa Skills with MongoDB & Golang
MongoDB .local Paris 2020: Realm : l'ingrédient secret pour de meilleures app...
MongoDB .local Paris 2020: Upply @MongoDB : Upply : Quand le Machine Learning...

Recently uploaded (20)

PDF
Chapter 3 Spatial Domain Image Processing.pdf
PPTX
Spectroscopy.pptx food analysis technology
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Empathic Computing: Creating Shared Understanding
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Machine learning based COVID-19 study performance prediction
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
cuic standard and advanced reporting.pdf
PPTX
Big Data Technologies - Introduction.pptx
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Chapter 3 Spatial Domain Image Processing.pdf
Spectroscopy.pptx food analysis technology
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Reach Out and Touch Someone: Haptics and Empathic Computing
Per capita expenditure prediction using model stacking based on satellite ima...
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
NewMind AI Weekly Chronicles - August'25 Week I
Empathic Computing: Creating Shared Understanding
“AI and Expert System Decision Support & Business Intelligence Systems”
Machine learning based COVID-19 study performance prediction
The AUB Centre for AI in Media Proposal.docx
Encapsulation_ Review paper, used for researhc scholars
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
cuic standard and advanced reporting.pdf
Big Data Technologies - Introduction.pptx
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton

Mongo+java (1)

  • 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 norberto@mongodb.com 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 info@mongodb.com

Editor's Notes

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