In this example, we are going to use MapReduce to find out how many articles there are in the database per author. The output of this operation will be a collection of documents, where each document will contain an author name and the number of articles written by the author.
1. Fire up the
mongo
shell and switch to themyblogsite
database:$./mongodb/bin/mongo MongoDB shell version: 1.8.1 connecting to: test >use myblogsite switched to db myblogsite >
2. Define the
map
function using the following command in the shell:>var map = function() { emit(this.author, 1); }
3. Now, define the
reduce
function:> var reduce = function(key, values) { ...var count = 0; ...for (var i = 0; i < values.length; i++){ ... count += values[i]; ... } ... return count; ... }; >
4. Apply the MapReduce operation on the
sample_articles
collection using the next command:> db.runCommand({ ... mapreduce: 'sample_articles', ....