1. Java Development
Eliot Horowitz
@eliothorowitz
MongoBoston
September 20, 2010
2. Java Choices
• Straight driver - map like interface
• Reflection - slow but easy
• Morphia - annotation based
3. Simple Java
Mongo m = new Mongo();
DB db = m.getDB( “myapp” );
DBCollection users = db.getCollection( “users” );
BasicDBObject person = new BasicDBObject();
person.put( “name” , “Eliot” );
person.put( “creation_date” , new java.util.Date()
users.insert( person );
5. Concurrency
• Ideally 1 Mongo instance per JVM
• Connection pooling built in
• Connections sticky to threads
• Force with requestStart/End
6. WriteConcern
• By default writes are fire and forget
• Can set WriteConcern on
Mongo,DB,DBCollection or per write call
• Configurable fsync, w=, wtimeout=
• Will throw exceptions for unique key
exceptions, etc...
• WriteResult will either cache result or call
getLastError if possible.
11. Mapper
public static class TokenizerMapper extends Mapper<Object, BSONObject, Text, IntWritable>{
private final static IntWritable one = new IntWritable(1);
private Text word = new Text();
public void map(Object key, BSONObject value, Context context )
throws IOException, InterruptedException {
StringTokenizer itr = new StringTokenizer(value.get( "x" ).toString());
while (itr.hasMoreTokens()) {
word.set(itr.nextToken());
context.write(word, one);
}
}
}
12. Reducer
public static class IntSumReducer extends Reducer<Text,IntWritable,Text,IntWritable> {
private IntWritable result = new IntWritable();
public void reduce(Text key, Iterable<IntWritable> values, Context context )
throws IOException, InterruptedException {
int sum = 0;
for (IntWritable val : values) {
sum += val.get();
}
result.set(sum);
context.write(key, result);
}
}