title: Grouping by value of Key in Mongo?
body: <p>Say I have some data that look something like this.</p>
  
  <pre><code>[
    { "foo": 1, "bar": "a" },
    { "foo": 2, "bar": "b" },
    { "foo": 3, "bar": "b" },
    { "foo": 4, "bar": "a" }
  ]
  </code></pre>
  
  <p>And I want group the rows by <code>bar</code>, and store the matching results under the value of bar in a object/map like data structure, something like this.</p>
  
  <pre><code>{
    "a": [{ "foo": 1, "bar": "a" }, { "foo": 4, "bar": "a" }],
    "b": [{ "foo": 2, "bar": "b" }, { "foo": 3, "bar": "b" }]
  }
  </code></pre>
  
  <p>What kind of functionality is there in Mongo to handle this kind of transformation (or something remotely similar)?</p>
  
  <h3>My Current Approach</h3>
  
  <p>I'm writing a web application using node.js, and I've managed to do this transformation in javascript (I know...), however whenever a user query is too open ended with very few constraints, it results in a memory over allocation, as I'm dealing with roughly more than 250,000 rows. My grouping method works when the query returns less than 10000ish rows.</p>
  
  <p>After this, I've realised I should probably get Mongo to handle this for me especially since it causes the server to hang until the grouping is done. I'm just unsure how to perform such a transformation.</p>
  
  <h3>A Eariler Approach</h3>
  
  <p>Before I tried to get web workers on the client to do it after transferring the data by web sockets &amp; split the job via web workers but it made the interface chug very noticeably, &amp; it likely wouldn't be stand up under pressure. But at least this didn't block the server, or crash my server.</p>
  
  <h3>More Information</h3>
  
  <p>Say if have a list of all the possible values of <code>bar</code> (which I have stored in a collection), should I just make multiple queries? &amp; from the results form the data structure?</p>