title: Count of MongoDB aggregation match results
body: <p>I'm working with a MongoDB collection that has a lot of duplicate keys. I regularly do aggregation queries to find out what those duplicates are, so that I can dig in and find out what is and isn't different about them.</p>
  
  <p>Unfortunately the database is huge and duplicates are often intentional. What I'd like to do is to find the <strong>count</strong> of keys that have duplicates, instead of printing a result with thousands of lines of output. Is this possible?</p>
  
  <p>(Side Note: I do all of my querying through the shell, so solutions that don't require external tools or a lot of code would be preferred, but I understand that's not always possible.)</p>
  
  <p>Example Records:</p>
  
  <pre><code>{ "_id" : 1, "type" : "example", "key" : "111111", "value" : "abc" }
  { "_id" : 2, "type" : "example", "key" : "222222", "value" : "def" }
  { "_id" : 3, "type" : "example", "key" : "222222", "value" : "ghi" }
  { "_id" : 4, "type" : "example", "key" : "333333", "value" : "jkl" }
  { "_id" : 5, "type" : "example", "key" : "333333", "value" : "mno" }
  { "_id" : 6, "type" : "example", "key" : "333333", "value" : "pqr" }
  { "_id" : 7, "type" : "example", "key" : "444444", "value" : "stu" }
  { "_id" : 8, "type" : "example", "key" : "444444", "value" : "vwx" }
  { "_id" : 9, "type" : "example", "key" : "444444", "value" : "yz1" }
  { "_id" : 10, "type" : "example", "key" : "444444", "value" : "234" }
  </code></pre>
  
  <p>Here is the query that I've been using to find duplicates based on <code>key</code>:</p>
  
  <pre><code>db.collection.aggregate([
      {
          $match: {
              type: "example"
          }
      },
      {
          $group: {
              _id: "$key",
              count: {
                  $sum: 1
              }
          }
      },
      {
          $match: {
              count: {
                  $gt: 1
              }
          }
      }
  ])
  </code></pre>
  
  <p>Which gives me an output of:</p>
  
  <pre><code>{
    "_id": "222222",
    "count": 2
  },
  {
    "_id": "333333",
    "count": 3
  },
  {
    "_id": "444444",
    "count": 4
  }
  </code></pre>
  
  <p>The result I want to get instead:</p>
  
  <pre><code>3
  </code></pre>