Skip to content
collinsauve edited this page Sep 24, 2010 · 3 revisions

Map Reduce

Map-Reduce is a huge topic. We won’t go into the details here, but basically it is a method to process huge datasets. You can read more here.

MongoDB-CSharp supports Map-Reduce in 2 ways.

Documents (hand crafted map-reduce)

You’d want to hand craft some map reduce functions if you need to do some aggregation that isn’t supported through our Linq provider. In addition, there are some additional properties to exploit, such as keeping the results in the database for future querying that can’t be done (currently) using the Linq provider.

//Compose a map reduce to get the sum everyone's ages.  

var mr = collection.MapReduceBuilder()
  .Map("function() { emit(1, { sum: this.age })}")
  .Reduce("function(key, values) { 
           var sum = 0;
           values.forEach(function(doc) {
             sum += doc.age;
           });
         return { sum: sum }
      }");

var sum = mr.Documents.First().Get<Document>("value").Get<int>("sum");

Linq

Linq is by far an easier way to compose map-reduce functions. Below is the same aggregation as above.

//Compose a map reduce to get the sum everyone's ages.  

var sum = collection.Linq().Sum(x => x.Age);

Essentially, we’ll just build the above, hand-crafted map-reduce for you. The more crazy you get, the better off you’ll be using the Linq provider.

//Compose a map reduce to get the age range of everyone grouped by the first letter of their last name.

var ageRanges = 
     from p in collection.Linq()
     group p by p.LastName[0] into g
     select new
     {
          FirstLetter = g.Key,
          AverageAge = g.Average(x => x.Age),
          MinAge = g.Min(x => x.Age),
          MaxAge = g.Max(x => x.Age)
     };

Supported Aggregates

We’ll be adding support for more aggregates as they are needed. Below is the list of currently supported aggregates.

  • Count
  • Sum
  • Min
  • Max
  • Average