title: MongoDB MapReduce Stats Engine
body: <p>I'm trying to develop a generic reporting engine for a MongoDB system which will aggregate information from a set of documents.  I won't know the structure of the documents in advance of the query running.</p>
  
  <p>e.g. One set of documents might look like this:</p>
  
  <pre><code>{"drink": "Tea","accompaniments": ["Biscuits","Crisps"]}
  {"drink": "Tea","accompaniments": ["Biscuits"]}
  {"drink": "Coffee","accompaniments": ["Biscuits","Crisps"]}
  {"drink": "Coffee","accompaniments": ["Nuts","Biscuits"]}
  {"drink": "Beer","accompaniments": ["Nuts","Crisps"]}
  {"drink": "Beer","accompaniments": ["Nuts"]}
  {"drink": "Beer","accompaniments": ["Crisps"]}
  </code></pre>
  
  <p>Here, I need results such as:</p>
  
  <pre><code>{drink:{Tea:2,Coffee:2,Beer:3},accompaniments:{biscuits:4,Crisps:4,Nuts:3}}
  </code></pre>
  
  <p>Another document set might look like this:</p>
  
  <pre><code>{"favcolor": "Red","shapes": ["Square","Circle"]}
  {"favcolor": "Red","shapes": ["Square"]}
  {"favcolor": "Green","shapes": ["Circle"]}
  </code></pre>
  
  <p>There may be any number of different document formats.</p>
  
  <p>So, I can't 'hard-code' the map-reduce functions with named keys.  Also, notice that I need to grab info from nested arrays and/or documents - I am in control of how the documents are built, so, to use one example, I could make the accompaniments array a proper set of nested documents if need be (in this example they're built from multiple-choice check-boxes).</p>
  
  <p>What would be the most efficient map-reduce function to grab all the stats from each set of documents?  I'm really hoping that there will be 'one' map-reduce that will be able to grab the data from each set.  Thanks very much.</p>