|
using System;
using System.Collections.Generic;
using System.Linq;
namespace TestMongo
{
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
public partial class Program
{
public static void DemoMapReduce(MongoCollection<ClubMember> collection)
{
//The match function has to be written in JavaScript
//the map method outputs a key value pair for each document
//in this case the key is the Lastname property value and the value is the Age property value
var map =
new BsonJavaScript(
@"function()
{
//Associate each LastName property with the Age value
emit(this.Lastname,this.Age);
}");
//The MapReduce method uses the output from the Map method
// to produce a list of ages for each unique LastName value.
// Then each key and its associated list of values is presented to the Reduce method in turn.
var reduce =
new BsonJavaScript(
@"function(lastName,ages)
{
return Array.sum(ages);
}");
//The Reduce method returns the Lastname as the key and the sum of the ages as the value
//The beauty of this technique is that data can be processed in batches
//The output of one batch is combined with that of another and fed back through the Reducer
//This is repeated until the output is reduced to the number of unique keys.
// The results are output to a new collection named ResultsCollection on the server.
// This saves on the use of computer memory and enables the results to be queried effectively by using indexes.
IEnumerable<BsonDocument> resultAsBsonDocumentCollection =
collection.MapReduce(map, reduce, MapReduceOptions.SetOutput(MapReduceOutput.Replace("Reduce"))).
GetResults();
Console.WriteLine("The total age for every member of each family is ....");
var reduction =
resultAsBsonDocumentCollection.Select(
doc => new { family = doc["_id"].AsString, age = (int)doc["value"].AsDouble });
foreach (var anon in reduction)
{
Console.WriteLine("{0} Family Total Age {1}", anon.family, anon.age);
}
}
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.