poiati/gmongo

Usage question. Mapreduce with finalize

patb23 opened this issue · 1 comments

Hi,
I have posted a question on Stackoverflow on how to use Finalize.
http://stackoverflow.com/questions/24723350/gmongo-mapreducer-with-finalizer
As explained in the post, was not able to use the mapreducecommand. Could I get help here?
Thanks

Hello patb23,

Sorry for my late response, here is a working example:

@Grab(group='com.gmongo', module='gmongo', version='1.2')
import com.gmongo.GMongo
import com.mongodb.MapReduceCommand
import com.mongodb.BasicDBObject

def mongo = new GMongo()
def db = mongo.getDB("gmongo")

def words = ['foo', 'bar', 'baz']
def rand  = new Random()        

db.words.drop()

1000.times { 
    db.words << [word: words[rand.nextInt(3)]]
}

assert db.words.count() == 1000

def map = """
    function map() {
        emit(this.word, {count: 1})
    }
    """

def reduce = """
    function reduce(key, values) {
        var count = 0
        for (var i = 0; i < values.length; i++)
            count += values[i].count
        return {count: count}
    }
    """

def finalize = """
    function finalize(key, reducedValue) {
        return {count: reducedValue.count.toString()}
    }
    """

def command = new MapReduceCommand(db.words, map, reduce, 'mrresult', MapReduceCommand.OutputType.REPLACE, new BasicDBObject())

command.setFinalize(finalize)

db.words.mapReduce(command)

println db.mrresult.findOne()

The finalize is just converting the count to a String.