No SQL > Mongo DB > How to execute Map and Reduce Algorithm with Finalizer
How to execute Map and Reduce Algorithm with Finalizer
MongoDB is a scalable, high-performance, open source NoSQL database.
It offers Ad hoc queries, Indexing, Replication, Load balancing, File storage (GridFS), Aggregation,
MapReduce and Server-side JavaScript execution.
This requires the library mongo-2.8.0.jar to be present in the classpath.
The following example shows how to execute map reduce algorithm with Finalizer in MongoDB.
/**
* @param args
* @throws MongoException
* @throws UnknownHostException
*/ public static void main(String[] args) throws UnknownHostException, MongoException {
//Connect to mongoDB with given IP and PORT
Mongo mongo = new Mongo("localhost", 27017);
//Get the database object
DB db = mongo.getDB("mydb");
// get a single collection
DBCollection collection = db.getCollection("things");
System.out.println(collection.toString());
// get all available documents
DBCursor cursor = collection.find(); while (cursor.hasNext()) {
System.out.println("Doc : " + cursor.next());
}
//Limit the data set
DBObject compoundquery = new BasicDBObject();
//compoundquery.put("_id", new BasicDBObject("$gt", 1)); // i.e. find all where _id > 2
compoundquery.put("_id", new BasicDBObject("$gt", 1).append("$lte", 4)); // i.e. 1 < _id <= 4
// Execute the map reduce function
MapReduceCommand mr = new MapReduceCommand(
collection, map, reduce, null,
MapReduceCommand.OutputType.INLINE, compoundquery);
mr.setFinalize(finalize);
mr.setVerbose(true); //true by default
// Execute the map reduce
MapReduceOutput out = collection.mapReduce(mr);