Harshil
Harshil

Reputation: 894

MongoDB Java Driver 3.0 MapReduce

This is the code I'm using to run map reduce on sourceCollectionName and to get the output to targetCollectionName. But the targetCollectionName is never created.

 new MongoClient("localhost").getDatabase(dbName).getCollection(sourceCollectionName)
                .mapReduce(map, reduce)
                    .action(MapReduceAction.REPLACE)
                    .databaseName(dbName)
                    .collectionName(targetCollectionName)
                    .sharded(false);

Although I'm able to get output as MapReduceIterable and when I iterate this the result is dumped as expected. Is this the right way to do it ?

MapReduceIterable mapReduceIterable = new MongoClient("localhost").getDatabase(dbName).getCollection(sourceCollectionName)
                .mapReduce(map, reduce)
                    .action(MapReduceAction.REPLACE)
                    .databaseName(dbName)
                    .collectionName(targetCollectionName)
                    .sharded(false);

for(Object o:mapReduceIterable){
     //Just Iterating makes map reduce to dump output collection
}

Upvotes: 3

Views: 1657

Answers (2)

cmvf
cmvf

Reputation: 1

Try following:

new MongoClient("localhost").getDatabase(dbName).getCollection(sourceCollectionName)
            .mapReduce(map, reduce)
                .action(MapReduceAction.REPLACE)
                .databaseName(dbName)
                .collectionName(targetCollectionName)
                .sharded(false)
                .toCollection()

Upvotes: 0

jyemin
jyemin

Reputation: 3813

Yes, this is the expected behavior. Since the MapReduceIterable is a fluent interface, there must be some way to signal the driver that it's time to actually do the map-reduce, and currently the only way to do that is to start iterating. If you really don't need the results, and want to short-cut the iteration, you can call the first() method instead (ignoring the result), which will return the first document and immediately close the cursor on the target collection.

Upvotes: 6

Related Questions