You are on page 1of 58

Java Development with MongoDB

Brendan W. McAdams

Novus Partners, Inc.


http://novus.com

May 2010 / Mongo NYC

Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 1 / 44
Outline

1 MongoDB + Java Basics


Setting up your Java environment
Connecting to MongoDB

2 Working with MongoDB


Collections + Documents
Inserting Documents to MongoDB
Querying MongoDB
AltJVM Languages - Syntactic Sugar
Indexes, etc

3 Final Remarks

Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 2 / 44
Outline

1 MongoDB + Java Basics


Setting up your Java environment
Connecting to MongoDB

2 Working with MongoDB


Collections + Documents
Inserting Documents to MongoDB
Querying MongoDB
AltJVM Languages - Syntactic Sugar
Indexes, etc

3 Final Remarks

Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 3 / 44
Adding the MongoDB Driver To Your Project

Assuming you’re using a dependency manager, make setup simple. . .

Listing 1: Maven Dependency


<dependency >
<groupId >org . mongodb < / groupId >
< a r t i f a c t I d >mongo−java−d r i v e r < / a r t i f a c t I d >
< v e r s i o n >1.4 </ v e r s i o n >
</ dependency >

Listing 2: Ivy Dependency


<dependency org= " org . mongodb "
name= " mongo−java−d r i v e r "
rev=" 1.4 " / >

Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 5 / 44
Adding the MongoDB Driver To Your Project

Assuming you’re using a dependency manager, make setup simple. . .

Listing 3: Maven Dependency


<dependency >
<groupId >org . mongodb < / groupId >
< a r t i f a c t I d >mongo−java−d r i v e r < / a r t i f a c t I d >
< v e r s i o n >1.4 </ v e r s i o n >
</ dependency >

Listing 4: Ivy Dependency


<dependency org= " org . mongodb "
name= " mongo−java−d r i v e r "
rev=" 1.4 " / >

Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 5 / 44
Outline

1 MongoDB + Java Basics


Setting up your Java environment
Connecting to MongoDB

2 Working with MongoDB


Collections + Documents
Inserting Documents to MongoDB
Querying MongoDB
AltJVM Languages - Syntactic Sugar
Indexes, etc

3 Final Remarks

Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 6 / 44
Simple Connection

Getting connected to MongoDB is simple; Connections are pooled, so


you only need one. . .
i m p o r t com . mongodb . Mongo ;
i m p o r t com . mongodb .DB;
Mongo m = new Mongo ( ) ;
Mongo m = new Mongo ( " l o c a l h o s t " ) ;
Mongo m = new Mongo ( " l o c a l h o s t " , 27017) ;

Fetch a Database Handle (lazy). . .


DB db = m. getDB ( " javaDemo " ) ;

If you need to authenticate. . .


boolean auth = db . a u t h e n t i c a t e ( " l o g i n " , " password " ) ;

Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 8 / 44
Simple Connection

Getting connected to MongoDB is simple; Connections are pooled, so


you only need one. . .
i m p o r t com . mongodb . Mongo ;
i m p o r t com . mongodb .DB;
Mongo m = new Mongo ( ) ;
Mongo m = new Mongo ( " l o c a l h o s t " ) ;
Mongo m = new Mongo ( " l o c a l h o s t " , 27017) ;

Fetch a Database Handle (lazy). . .


DB db = m. getDB ( " javaDemo " ) ;

If you need to authenticate. . .


boolean auth = db . a u t h e n t i c a t e ( " l o g i n " , " password " ) ;

Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 8 / 44
Simple Connection

Getting connected to MongoDB is simple; Connections are pooled, so


you only need one. . .
i m p o r t com . mongodb . Mongo ;
i m p o r t com . mongodb .DB;
Mongo m = new Mongo ( ) ;
Mongo m = new Mongo ( " l o c a l h o s t " ) ;
Mongo m = new Mongo ( " l o c a l h o s t " , 27017) ;

Fetch a Database Handle (lazy). . .


DB db = m. getDB ( " javaDemo " ) ;

If you need to authenticate. . .


boolean auth = db . a u t h e n t i c a t e ( " l o g i n " , " password " ) ;

Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 8 / 44
Outline

1 MongoDB + Java Basics


Setting up your Java environment
Connecting to MongoDB

2 Working with MongoDB


Collections + Documents
Inserting Documents to MongoDB
Querying MongoDB
AltJVM Languages - Syntactic Sugar
Indexes, etc

3 Final Remarks

Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 9 / 44
Working with Collections

Collections are MongoDB "tables". . .


List all of the collections in a database. . .
Set < S t r i n g > = c o l l s = db . getCollectionNames ( ) ;
for ( String s : colls ) {
System . o u t . p r i n t l n ( s ) ;
}

Get a specific collection (lazy). . .


D B C o l l e c t i o n c o l l = db . g e t C o l l e c t i o n ( " t e s t D a t a " ) ;

Count the number of documents in a collection. . .


c o l l . getCount ( ) ;

Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 11 / 44
Working with Collections

Collections are MongoDB "tables". . .


List all of the collections in a database. . .
Set < S t r i n g > = c o l l s = db . getCollectionNames ( ) ;
for ( String s : colls ) {
System . o u t . p r i n t l n ( s ) ;
}

Get a specific collection (lazy). . .


D B C o l l e c t i o n c o l l = db . g e t C o l l e c t i o n ( " t e s t D a t a " ) ;

Count the number of documents in a collection. . .


c o l l . getCount ( ) ;

Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 11 / 44
MongoDB Documents
BSON

"Documents" are MongoDB’s "rows".


MongoDB’s Internal Document representation is ’BSON’
I BSON is a binary optimized flavor of JSON
I Corrects JSON’s inefficiency in string encoding (Base64)
I Supports extras including Regular Expressions, Byte Arrays,
DateTimes & Timestamps, as well as datatypes for Javascript code
blocks & functions.
I Creative Commons licensed.
I BSON implementation being split into its own package in most
drivers.
I bsonspec.org

Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 12 / 44
MongoDB Documents
From Java: BasicDBObject

Java representation of BSON is the map-like DBObject (Java 2.0


driver has a new base class of BSONObject related to the BSON
split-off)
Easiest way to work with Mongo Documents is BasicDBObject. . .
I BasicDBObject implements java.util.LinkedHashMap<String,
Object>
I Mutable object
I Can take a Map as a constructor parameter
I Example:
DBObject doc = new BasicDBObject ( ) ;
doc . p u t ( " username " , " bwmcadams " ) ;
doc . p u t ( " password " , "MongoNYC" ) ;

I toString returns a JSON serialization.


Use BasicDBList (implements java.util.ArrayList<Object>) to
represent Arrays.

Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 14 / 44
MongoDB Documents
From Java: BasicDBObject

Java representation of BSON is the map-like DBObject (Java 2.0


driver has a new base class of BSONObject related to the BSON
split-off)
Easiest way to work with Mongo Documents is BasicDBObject. . .
I BasicDBObject implements java.util.LinkedHashMap<String,
Object>
I Mutable object
I Can take a Map as a constructor parameter
I Example:
DBObject doc = new BasicDBObject ( ) ;
doc . p u t ( " username " , " bwmcadams " ) ;
doc . p u t ( " password " , "MongoNYC" ) ;

I toString returns a JSON serialization.


Use BasicDBList (implements java.util.ArrayList<Object>) to
represent Arrays.

Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 14 / 44
MongoDB Documents
From Java: BasicDBObject

Java representation of BSON is the map-like DBObject (Java 2.0


driver has a new base class of BSONObject related to the BSON
split-off)
Easiest way to work with Mongo Documents is BasicDBObject. . .
I BasicDBObject implements java.util.LinkedHashMap<String,
Object>
I Mutable object
I Can take a Map as a constructor parameter
I Example:
DBObject doc = new BasicDBObject ( ) ;
doc . p u t ( " username " , " bwmcadams " ) ;
doc . p u t ( " password " , "MongoNYC" ) ;

I toString returns a JSON serialization.


Use BasicDBList (implements java.util.ArrayList<Object>) to
represent Arrays.

Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 14 / 44
MongoDB Documents
From Java: BasicDBObject

Java representation of BSON is the map-like DBObject (Java 2.0


driver has a new base class of BSONObject related to the BSON
split-off)
Easiest way to work with Mongo Documents is BasicDBObject. . .
I BasicDBObject implements java.util.LinkedHashMap<String,
Object>
I Mutable object
I Can take a Map as a constructor parameter
I Example:
DBObject doc = new BasicDBObject ( ) ;
doc . p u t ( " username " , " bwmcadams " ) ;
doc . p u t ( " password " , "MongoNYC" ) ;

I toString returns a JSON serialization.


Use BasicDBList (implements java.util.ArrayList<Object>) to
represent Arrays.

Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 14 / 44
MongoDB Documents
From Java: BasicDBObject

Java representation of BSON is the map-like DBObject (Java 2.0


driver has a new base class of BSONObject related to the BSON
split-off)
Easiest way to work with Mongo Documents is BasicDBObject. . .
I BasicDBObject implements java.util.LinkedHashMap<String,
Object>
I Mutable object
I Can take a Map as a constructor parameter
I Example:
DBObject doc = new BasicDBObject ( ) ;
doc . p u t ( " username " , " bwmcadams " ) ;
doc . p u t ( " password " , "MongoNYC" ) ;

I toString returns a JSON serialization.


Use BasicDBList (implements java.util.ArrayList<Object>) to
represent Arrays.

Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 14 / 44
MongoDB Documents
From Java: BasicDBObject

Java representation of BSON is the map-like DBObject (Java 2.0


driver has a new base class of BSONObject related to the BSON
split-off)
Easiest way to work with Mongo Documents is BasicDBObject. . .
I BasicDBObject implements java.util.LinkedHashMap<String,
Object>
I Mutable object
I Can take a Map as a constructor parameter
I Example:
DBObject doc = new BasicDBObject ( ) ;
doc . p u t ( " username " , " bwmcadams " ) ;
doc . p u t ( " password " , "MongoNYC" ) ;

I toString returns a JSON serialization.


Use BasicDBList (implements java.util.ArrayList<Object>) to
represent Arrays.

Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 14 / 44
MongoDB Documents
From Java: BasicDBObject

Java representation of BSON is the map-like DBObject (Java 2.0


driver has a new base class of BSONObject related to the BSON
split-off)
Easiest way to work with Mongo Documents is BasicDBObject. . .
I BasicDBObject implements java.util.LinkedHashMap<String,
Object>
I Mutable object
I Can take a Map as a constructor parameter
I Example:
DBObject doc = new BasicDBObject ( ) ;
doc . p u t ( " username " , " bwmcadams " ) ;
doc . p u t ( " password " , "MongoNYC" ) ;

I toString returns a JSON serialization.


Use BasicDBList (implements java.util.ArrayList<Object>) to
represent Arrays.

Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 14 / 44
MongoDB Documents
From Java: BasicDBObjectBuilder

For those who prefer immutability. . .


BasicDBObjectBuilder follows the Builder pattern.
add() your keys & values:
BasicDBObjectBuilder b u i l d e r = BasicDBObjectBuilder . s t a r t ( ) ;
b u i l d e r . add ( " username " , " bwmcadams " ) ;
b u i l d e r . add ( " password " , "MongoNYC" ) ;
b u i l d e r . add ( " p r e s e n t a t i o n " , " Java Development w i t h MongoDB" ) ;

A BasicDBObjectBuilder is not a DBObject.


Call get() to return the built-up DBObject.
add() returns itself so you can chain calls instead:
BasicDBOBjectBuilder . s t a r t ( ) . add ( " username " , " bwmcadams " ) . add ( "
password " , "MongoNYC" ) . add ( " p r e s e n t a t i o n " , " Java Development
w i t h MongoDB" ) . g e t ( ) ;

Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 16 / 44
MongoDB Documents
From Java: BasicDBObjectBuilder

For those who prefer immutability. . .


BasicDBObjectBuilder follows the Builder pattern.
add() your keys & values:
BasicDBObjectBuilder b u i l d e r = BasicDBObjectBuilder . s t a r t ( ) ;
b u i l d e r . add ( " username " , " bwmcadams " ) ;
b u i l d e r . add ( " password " , "MongoNYC" ) ;
b u i l d e r . add ( " p r e s e n t a t i o n " , " Java Development w i t h MongoDB" ) ;

A BasicDBObjectBuilder is not a DBObject.


Call get() to return the built-up DBObject.
add() returns itself so you can chain calls instead:
BasicDBOBjectBuilder . s t a r t ( ) . add ( " username " , " bwmcadams " ) . add ( "
password " , "MongoNYC" ) . add ( " p r e s e n t a t i o n " , " Java Development
w i t h MongoDB" ) . g e t ( ) ;

Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 16 / 44
MongoDB Documents
From Java: BasicDBObjectBuilder

For those who prefer immutability. . .


BasicDBObjectBuilder follows the Builder pattern.
add() your keys & values:
BasicDBObjectBuilder b u i l d e r = BasicDBObjectBuilder . s t a r t ( ) ;
b u i l d e r . add ( " username " , " bwmcadams " ) ;
b u i l d e r . add ( " password " , "MongoNYC" ) ;
b u i l d e r . add ( " p r e s e n t a t i o n " , " Java Development w i t h MongoDB" ) ;

A BasicDBObjectBuilder is not a DBObject.


Call get() to return the built-up DBObject.
add() returns itself so you can chain calls instead:
BasicDBOBjectBuilder . s t a r t ( ) . add ( " username " , " bwmcadams " ) . add ( "
password " , "MongoNYC" ) . add ( " p r e s e n t a t i o n " , " Java Development
w i t h MongoDB" ) . g e t ( ) ;

Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 16 / 44
MongoDB Documents
From Java: BasicDBObjectBuilder

For those who prefer immutability. . .


BasicDBObjectBuilder follows the Builder pattern.
add() your keys & values:
BasicDBObjectBuilder b u i l d e r = BasicDBObjectBuilder . s t a r t ( ) ;
b u i l d e r . add ( " username " , " bwmcadams " ) ;
b u i l d e r . add ( " password " , "MongoNYC" ) ;
b u i l d e r . add ( " p r e s e n t a t i o n " , " Java Development w i t h MongoDB" ) ;

A BasicDBObjectBuilder is not a DBObject.


Call get() to return the built-up DBObject.
add() returns itself so you can chain calls instead:
BasicDBOBjectBuilder . s t a r t ( ) . add ( " username " , " bwmcadams " ) . add ( "
password " , "MongoNYC" ) . add ( " p r e s e n t a t i o n " , " Java Development
w i t h MongoDB" ) . g e t ( ) ;

Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 16 / 44
MongoDB Documents
Implementation by Extension: DBObject

If you want to create your own concrete objects, extend &


implement DBObject
I Requires you implement a map-like interface including ability to get
& set fields by key (even if you don’t use them, required to
deserialize)
I Instances of DBObject can be saved directly to MongoDB.
Feeling Fancy? Reflect instead. . .
I Use ReflectionDBObject as a base class for your Beans.
I ReflectionDBObject uses reflection to proxy your getters & setters
and behave like a DBObject.
I Downside: With Java’s single inheritance you are stuck using this
as your base class.
Existing Object Model? ORM-Like Solutions. . .
I Morphia (uses JPA-style annotations)
I Daybreak (annotation based)
I Mungbean (more Java-ey query syntax & PoJo Mapping)

Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 17 / 44
MongoDB Documents
Implementation by Extension: DBObject

If you want to create your own concrete objects, extend &


implement DBObject
I Requires you implement a map-like interface including ability to get
& set fields by key (even if you don’t use them, required to
deserialize)
I Instances of DBObject can be saved directly to MongoDB.
Feeling Fancy? Reflect instead. . .
I Use ReflectionDBObject as a base class for your Beans.
I ReflectionDBObject uses reflection to proxy your getters & setters
and behave like a DBObject.
I Downside: With Java’s single inheritance you are stuck using this
as your base class.
Existing Object Model? ORM-Like Solutions. . .
I Morphia (uses JPA-style annotations)
I Daybreak (annotation based)
I Mungbean (more Java-ey query syntax & PoJo Mapping)

Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 17 / 44
MongoDB Documents
Implementation by Extension: DBObject

If you want to create your own concrete objects, extend &


implement DBObject
I Requires you implement a map-like interface including ability to get
& set fields by key (even if you don’t use them, required to
deserialize)
I Instances of DBObject can be saved directly to MongoDB.
Feeling Fancy? Reflect instead. . .
I Use ReflectionDBObject as a base class for your Beans.
I ReflectionDBObject uses reflection to proxy your getters & setters
and behave like a DBObject.
I Downside: With Java’s single inheritance you are stuck using this
as your base class.
Existing Object Model? ORM-Like Solutions. . .
I Morphia (uses JPA-style annotations)
I Daybreak (annotation based)
I Mungbean (more Java-ey query syntax & PoJo Mapping)

Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 17 / 44
Briefly: Working with DBObjects

Getting data from DBObjects is relatively simple in Java. . .


Check if a field (a.k.a. Key) exists with containsField()
Get a Set<String> of a DBObject’s field names with keySet()
Get a specific field with get(String key). This returns Object so you
will need to cast to an expected value.
/ / DBObject doc = <some row f e t c h e d from MongoDB>
S t r i n g username = ( S t r i n g ) doc . g e t ( " username " )

Call toMap() to get back a Map (String, Object) instead.

Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 19 / 44
Briefly: Working with DBObjects

Getting data from DBObjects is relatively simple in Java. . .


Check if a field (a.k.a. Key) exists with containsField()
Get a Set<String> of a DBObject’s field names with keySet()
Get a specific field with get(String key). This returns Object so you
will need to cast to an expected value.
/ / DBObject doc = <some row f e t c h e d from MongoDB>
S t r i n g username = ( S t r i n g ) doc . g e t ( " username " )

Call toMap() to get back a Map (String, Object) instead.

Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 19 / 44
Briefly: Working with DBObjects

Getting data from DBObjects is relatively simple in Java. . .


Check if a field (a.k.a. Key) exists with containsField()
Get a Set<String> of a DBObject’s field names with keySet()
Get a specific field with get(String key). This returns Object so you
will need to cast to an expected value.
/ / DBObject doc = <some row f e t c h e d from MongoDB>
S t r i n g username = ( S t r i n g ) doc . g e t ( " username " )

Call toMap() to get back a Map (String, Object) instead.

Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 19 / 44
Briefly: Working with DBObjects

Getting data from DBObjects is relatively simple in Java. . .


Check if a field (a.k.a. Key) exists with containsField()
Get a Set<String> of a DBObject’s field names with keySet()
Get a specific field with get(String key). This returns Object so you
will need to cast to an expected value.
/ / DBObject doc = <some row f e t c h e d from MongoDB>
S t r i n g username = ( S t r i n g ) doc . g e t ( " username " )

Call toMap() to get back a Map (String, Object) instead.

Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 19 / 44
Briefly: Working with DBObjects

Getting data from DBObjects is relatively simple in Java. . .


Check if a field (a.k.a. Key) exists with containsField()
Get a Set<String> of a DBObject’s field names with keySet()
Get a specific field with get(String key). This returns Object so you
will need to cast to an expected value.
/ / DBObject doc = <some row f e t c h e d from MongoDB>
S t r i n g username = ( S t r i n g ) doc . g e t ( " username " )

Call toMap() to get back a Map (String, Object) instead.

Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 19 / 44
Outline

1 MongoDB + Java Basics


Setting up your Java environment
Connecting to MongoDB

2 Working with MongoDB


Collections + Documents
Inserting Documents to MongoDB
Querying MongoDB
AltJVM Languages - Syntactic Sugar
Indexes, etc

3 Final Remarks

Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 20 / 44
Inserting Documents
One at a time:
DBObject doc =
BasicDBOBjectBuilder . s t a r t ( ) .
add ( " username " , " bwmcadams " ) .
add ( " password " , "MongoNYC" ) .
add ( " p r e s e n t a t i o n " , " Java Development w i t h MongoDB" ) .
get ( ) ;
/ / DBCollection c o l l
c o l l . i n s e r t ( doc ) ;

Got multiple documents? Call insert() in a loop, or pass


DBObject[] or List<DBObject>
Three ways to store your documents:
I I NSERT (insert()) always attempts to add a new row.
I S AVE (save()) only attempts to insert unless _id is defined.
Otherwise, it will attempt to update the identified document.
I U PDATE (update()) Allows you to pass a query to filter by and the
fields to change. Boolean option "multi" specifies if multiple
documents should be updated. Boolean "upsert" specifies that the
object should be inserted if it doesn’t exist (e.g. query doesn’t
match).
Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 22 / 44
Inserting Documents
One at a time:
DBObject doc =
BasicDBOBjectBuilder . s t a r t ( ) .
add ( " username " , " bwmcadams " ) .
add ( " password " , "MongoNYC" ) .
add ( " p r e s e n t a t i o n " , " Java Development w i t h MongoDB" ) .
get ( ) ;
/ / DBCollection c o l l
c o l l . i n s e r t ( doc ) ;

Got multiple documents? Call insert() in a loop, or pass


DBObject[] or List<DBObject>
Three ways to store your documents:
I I NSERT (insert()) always attempts to add a new row.
I S AVE (save()) only attempts to insert unless _id is defined.
Otherwise, it will attempt to update the identified document.
I U PDATE (update()) Allows you to pass a query to filter by and the
fields to change. Boolean option "multi" specifies if multiple
documents should be updated. Boolean "upsert" specifies that the
object should be inserted if it doesn’t exist (e.g. query doesn’t
match).
Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 22 / 44
Inserting Documents
One at a time:
DBObject doc =
BasicDBOBjectBuilder . s t a r t ( ) .
add ( " username " , " bwmcadams " ) .
add ( " password " , "MongoNYC" ) .
add ( " p r e s e n t a t i o n " , " Java Development w i t h MongoDB" ) .
get ( ) ;
/ / DBCollection c o l l
c o l l . i n s e r t ( doc ) ;

Got multiple documents? Call insert() in a loop, or pass


DBObject[] or List<DBObject>
Three ways to store your documents:
I I NSERT (insert()) always attempts to add a new row.
I S AVE (save()) only attempts to insert unless _id is defined.
Otherwise, it will attempt to update the identified document.
I U PDATE (update()) Allows you to pass a query to filter by and the
fields to change. Boolean option "multi" specifies if multiple
documents should be updated. Boolean "upsert" specifies that the
object should be inserted if it doesn’t exist (e.g. query doesn’t
match).
Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 22 / 44
Inserting Documents
One at a time:
DBObject doc =
BasicDBOBjectBuilder . s t a r t ( ) .
add ( " username " , " bwmcadams " ) .
add ( " password " , "MongoNYC" ) .
add ( " p r e s e n t a t i o n " , " Java Development w i t h MongoDB" ) .
get ( ) ;
/ / DBCollection c o l l
c o l l . i n s e r t ( doc ) ;

Got multiple documents? Call insert() in a loop, or pass


DBObject[] or List<DBObject>
Three ways to store your documents:
I I NSERT (insert()) always attempts to add a new row.
I S AVE (save()) only attempts to insert unless _id is defined.
Otherwise, it will attempt to update the identified document.
I U PDATE (update()) Allows you to pass a query to filter by and the
fields to change. Boolean option "multi" specifies if multiple
documents should be updated. Boolean "upsert" specifies that the
object should be inserted if it doesn’t exist (e.g. query doesn’t
match).
Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 22 / 44
Outline

1 MongoDB + Java Basics


Setting up your Java environment
Connecting to MongoDB

2 Working with MongoDB


Collections + Documents
Inserting Documents to MongoDB
Querying MongoDB
AltJVM Languages - Syntactic Sugar
Indexes, etc

3 Final Remarks

Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 23 / 44
MongoDB Querying
Basics

Find a single row with findOne(). Takes the first row returned.
Getting a cursor of all documents (find() with no query):
DBCursor c u r = c o l l . f i n d ( ) ;
w h i l e ( DBObject doc : c u r ) {
System . o u t . p r i n t l n ( doc ) ;
}

Query for a specific value. . .


DBObject q = new B a s i c D B O b j e c t B u i l d e r .
start () .
add ( " username " , " bwmcadams " ) .
get ( ) ;
DBObject doc = c o l l . findOne ( q ) ;

Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 25 / 44
MongoDB Querying
Basics

Find a single row with findOne(). Takes the first row returned.
Getting a cursor of all documents (find() with no query):
DBCursor c u r = c o l l . f i n d ( ) ;
w h i l e ( DBObject doc : c u r ) {
System . o u t . p r i n t l n ( doc ) ;
}

Query for a specific value. . .


DBObject q = new B a s i c D B O b j e c t B u i l d e r .
start () .
add ( " username " , " bwmcadams " ) .
get ( ) ;
DBObject doc = c o l l . findOne ( q ) ;

Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 25 / 44
MongoDB Querying
Basics

Find a single row with findOne(). Takes the first row returned.
Getting a cursor of all documents (find() with no query):
DBCursor c u r = c o l l . f i n d ( ) ;
w h i l e ( DBObject doc : c u r ) {
System . o u t . p r i n t l n ( doc ) ;
}

Query for a specific value. . .


DBObject q = new B a s i c D B O b j e c t B u i l d e r .
start () .
add ( " username " , " bwmcadams " ) .
get ( ) ;
DBObject doc = c o l l . findOne ( q ) ;

Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 25 / 44
MongoDB Querying
Basics

You can pass an optional second DBObject parameter to find()


and findOne() which specifies the fields to return.
If you have an embedded object (for example, an address object)
you can retrieve it with dot notation in the fields list (e.g.
"address.city" retrieves just the city value)
Use limit(), skip() and sort() on DBCursor to adjust your results.
These all return a new DBCursor.
distinct() can be used (on DBCollection to find all distinct values
for a given key; it returns a list:
L i s t values = c o l l . d i s t i n c t ( " postedBy " ) ; / / c o n t a i n s a l l d i s t i n c t
values i n " postedBy "
/ ∗ ∗ Or , l i m i t what you ’ r e l o o k i n g f o r w i t h a query ∗ /
DBObject q = new BasicDBObject ( " postedBy " ,
new BasicDBObject ( " $ne " , " bwmcadams " )
);
L i s t v a l u e s = c o l l . d i s t i n c t ( " postedBy " , q ) ;

Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 27 / 44
MongoDB Querying
Query Operators

MongoDB is no mere Key-Value store. There are myriad powerful


operators to enhance your MongoDB queries. . .
Conditional Operators: $gt (>), $lt (<), $gte (>=), $lte (<=)
Negative Equality: $ne (!=)
Array Operators: $in (SQL "IN" clause. . . takes an array), $nin (Opposite
of "IN"), $all (Requires all values in the array match), $size (Match the
size of an array)
Field Defined: $exists (boolean argument)(Great in a schemaless world)
Regular Expressions (Language dependent - most drivers support it)
Pass Arbitrary Javascript with $where (No OR statements, so use
WHERE for complex range filters)
Negate any operator with $not

Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 28 / 44
MongoDB Querying
Putting Operators to Work

Using a query operator requires nested objects. . .


All posts since a particular date:
DBObject q = new BasicDBObject ( " postDate " ,
new BasicDBObject ( " $gte " , new j a v a . u t i l . Date ( ) )
);
DBCursor p o s t s = c o l l . f i n d ( q ) ;

Find all posts NOT by me:


DBObject q = new BasicDBObject ( " postedBy " ,
new BasicDBObject ( " $ne " , " bwmcadams " )
);
DBCursor p o s t s = c o l l . f i n d ( q ) ;

No syntactic sugar in Java to make it easier. . .


Mungbean provides a more fluid query syntax (but isn’t very
Mongo-ey), if you use its PoJo mapping.
You might also consider evaluating other JVM languages for
querying....
Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 30 / 44
MongoDB Querying
Putting Operators to Work

Using a query operator requires nested objects. . .


All posts since a particular date:
DBObject q = new BasicDBObject ( " postDate " ,
new BasicDBObject ( " $gte " , new j a v a . u t i l . Date ( ) )
);
DBCursor p o s t s = c o l l . f i n d ( q ) ;

Find all posts NOT by me:


DBObject q = new BasicDBObject ( " postedBy " ,
new BasicDBObject ( " $ne " , " bwmcadams " )
);
DBCursor p o s t s = c o l l . f i n d ( q ) ;

No syntactic sugar in Java to make it easier. . .


Mungbean provides a more fluid query syntax (but isn’t very
Mongo-ey), if you use its PoJo mapping.
You might also consider evaluating other JVM languages for
querying....
Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 30 / 44
MongoDB Querying
Putting Operators to Work

Using a query operator requires nested objects. . .


All posts since a particular date:
DBObject q = new BasicDBObject ( " postDate " ,
new BasicDBObject ( " $gte " , new j a v a . u t i l . Date ( ) )
);
DBCursor p o s t s = c o l l . f i n d ( q ) ;

Find all posts NOT by me:


DBObject q = new BasicDBObject ( " postedBy " ,
new BasicDBObject ( " $ne " , " bwmcadams " )
);
DBCursor p o s t s = c o l l . f i n d ( q ) ;

No syntactic sugar in Java to make it easier. . .


Mungbean provides a more fluid query syntax (but isn’t very
Mongo-ey), if you use its PoJo mapping.
You might also consider evaluating other JVM languages for
querying....
Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 30 / 44
MongoDB Querying
Putting Operators to Work

Using a query operator requires nested objects. . .


All posts since a particular date:
DBObject q = new BasicDBObject ( " postDate " ,
new BasicDBObject ( " $gte " , new j a v a . u t i l . Date ( ) )
);
DBCursor p o s t s = c o l l . f i n d ( q ) ;

Find all posts NOT by me:


DBObject q = new BasicDBObject ( " postedBy " ,
new BasicDBObject ( " $ne " , " bwmcadams " )
);
DBCursor p o s t s = c o l l . f i n d ( q ) ;

No syntactic sugar in Java to make it easier. . .


Mungbean provides a more fluid query syntax (but isn’t very
Mongo-ey), if you use its PoJo mapping.
You might also consider evaluating other JVM languages for
querying....
Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 30 / 44
MongoDB Querying
Putting Operators to Work

Using a query operator requires nested objects. . .


All posts since a particular date:
DBObject q = new BasicDBObject ( " postDate " ,
new BasicDBObject ( " $gte " , new j a v a . u t i l . Date ( ) )
);
DBCursor p o s t s = c o l l . f i n d ( q ) ;

Find all posts NOT by me:


DBObject q = new BasicDBObject ( " postedBy " ,
new BasicDBObject ( " $ne " , " bwmcadams " )
);
DBCursor p o s t s = c o l l . f i n d ( q ) ;

No syntactic sugar in Java to make it easier. . .


Mungbean provides a more fluid query syntax (but isn’t very
Mongo-ey), if you use its PoJo mapping.
You might also consider evaluating other JVM languages for
querying....
Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 30 / 44
MongoDB Querying
Putting Operators to Work

Using a query operator requires nested objects. . .


All posts since a particular date:
DBObject q = new BasicDBObject ( " postDate " ,
new BasicDBObject ( " $gte " , new j a v a . u t i l . Date ( ) )
);
DBCursor p o s t s = c o l l . f i n d ( q ) ;

Find all posts NOT by me:


DBObject q = new BasicDBObject ( " postedBy " ,
new BasicDBObject ( " $ne " , " bwmcadams " )
);
DBCursor p o s t s = c o l l . f i n d ( q ) ;

No syntactic sugar in Java to make it easier. . .


Mungbean provides a more fluid query syntax (but isn’t very
Mongo-ey), if you use its PoJo mapping.
You might also consider evaluating other JVM languages for
querying....
Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 30 / 44
Outline

1 MongoDB + Java Basics


Setting up your Java environment
Connecting to MongoDB

2 Working with MongoDB


Collections + Documents
Inserting Documents to MongoDB
Querying MongoDB
AltJVM Languages - Syntactic Sugar
Indexes, etc

3 Final Remarks

Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 31 / 44
MongoDB Querying
AltJVM Languages - Syntactic Sugar

Listing 5: Groovy Sample


def q = [postDate: ["$gte:" new java.util.Date()]
] as BasicDBObject
def q = [postedBy: ["$ne": "bwmcadams"]
] as BasicDBObject

def posts = coll.find(q)

Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 33 / 44
MongoDB Querying
AltJVM Languages - Syntactic Sugar

Listing 6: Scala Sample


val q = "postDate" $gte new java.util.Date()
val q = "postedBy" $ne "bwmcadams"

val posts = coll.find(q)

Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 35 / 44
MongoDB Querying
AltJVM Languages - Syntactic Sugar

Listing 7: Jython Sample


q = {"postDate": {"$gte": datetime.datetime.now()}}
q = {"postedBy": {"$ne": "bwmcadams"}}

posts = coll.find(q)

Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 37 / 44
Outline

1 MongoDB + Java Basics


Setting up your Java environment
Connecting to MongoDB

2 Working with MongoDB


Collections + Documents
Inserting Documents to MongoDB
Querying MongoDB
AltJVM Languages - Syntactic Sugar
Indexes, etc

3 Final Remarks

Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 38 / 44
Indexes
MongoDB Indexes work much like RDBMS indexes. . .
Create a single-key index:
DBObject i d x = new BasicDBObject ( " postedBy " , 1 ) ;
c o l l . createIndex ( idx ) ;

This defaults to ascending order (-1 = descending), with a system


generated name.
For a multi-key/compound-key index:
DBObject i d x = new B a s i c D B O b j e c t B u i l d e r . s t a r t ( ) .
add ( " postedBy " , 1 ) .
add ( " postDate " , −1) .
get ( ) ;
c o l l . createIndex ( idx ) ;

This sorts postedBy ascending, but postDate descending.


If you want to index an embedded field, simply use the query dot
notation (e.g. "address.city")

Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 40 / 44
Indexes
Options

MongoDB Indexes work much like RDBMS indexes. . .


You can pass a second DBObject of options to change the type of index,
name, etc:
DBObject i d x = new BasicDBObject ( " s l u g " , 1 ) ;
DBObject o p t s = new BasicDBObject ( " unique " : t r u e ) ;
c o l l . createIndex ( idx , opts ) ;

This will ensure that the "slug" field is unique across all entries. (A list of
complete options is available in the MongoDB Documentation)
Consider using ensureIndex() instead of createIndex().

Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 42 / 44
Things We Didn’t Cover

Things we didn’t cover, but you should spend some time exploring. . .
Map/Reduce (great for more complex aggregation)
Geospatial indexes and queries
Aggregation queries such as Grouping statements (Which use
JavaScript functions)
GridFS (Efficient storage of large files)
Lots more at MongoDB.org . . .

Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 43 / 44
Contact Info + Where To Learn More
Contact Me
I twitter: @rit
I email: bwmcadams@gmail.com
Pressing Questions?
I IRC - freenode.net #mongodb
I MongoDB Users List -
http://groups.google.com/group/mongodb-user
Mongo Java Language Center - http:
//mongodb.org/display/DOCS/Java+Language+Center
(Links to Java driver docs, and many of the third party libraries)
Morphia - http://code.google.com/p/morphia/
Mungbean -
http://github.com/jannehietamaki/mungbean
Experimental JDBC Driver -
http://github.com/erh/mongo-jdbc

Brendan W. McAdams (Novus Partners, Inc.) Java Development with MongoDB Mongo NYC, May 2010 44 / 44

You might also like