title: MongoDB: Iterate over collection by key?
body: <p>How can I iterate over all documents matching each value of a specified key in a MongoDB collection?</p>
  
  <p>E.g. for a collection containing:</p>
  
  <pre><code>{ _id: ObjectId, keyA: 1 },
  { _id: ObjectId, keyA: 2 },
  { _id: ObjectId, keyA: 2 },
  </code></pre>
  
  <p>...with an index of <code>{ keyA: 1 }</code>, how can I run an operation on all documents where <code>keyA:1</code>, then <code>keyA:2</code>, and so on?</p>
  
  <p>Specifically, I want to run a count() of the documents for each <code>keyA</code> value.  So for this collection, the equivalent of <code>find({keyA:1}).count()</code>, <code>find({keyA:2}).count()</code>, etc.</p>
  
  <p><strong>UPDATE</strong>: whether or not the keys are indexed is irrelevant in terms of how they're iterated, so edited title and description to make Q/A easier to reference in the future.</p>