Tutorial for Averaging Over a field MongoDB using MapReduce
In performing the averaging of a numeric field for a mongodb the examples were relatively good for JavaScript but I couldn’t find anything that explained exactly how to do it in Java. The transitioning of steps to Java seemed like they should be easy but there was a step or two always missing.
To make this task as simple as possible I am going to include a starter file for you to use. You can then follow along in this tutorial adding the code as instructed and by the end of the tutorial you should have a working project that calculates the average of field in mongoDB.
Starter fileTo make things simple we will break this process down into five steps:
- Make MapReduceCommand Object.
- Mapping Function.
- Reducing Function
- Finalize Function
- Print Function
Make Map Reduce Command
Below is the code that creates A mapReduce Object all the code below is in Java.
Now the map reduce command takes six parameters. The first 3 are the ones I want to describe
in more detail. The first parameter is books, in this case books is the name of the DBCollection
we are using and this parameter has to be a DBCollection. The second parameter is the method that
contains the mapping function. The third parameter is for the method that has the reducing function.
The thing to notice here is there is no parameter for the finalize function(In JavaScript you can
insert a finalize statement). Since the MapReduceCommand constructor does not take a parameter for
the finalize parameter you will have to use the setFinalize() method of the MapReduceCommand object
passing it a parameter of the finalize command.