title: Create MongoDB fields with names based on sub-document values using aggregation pipeline?
body: <p>Given a MongoDB collection with the following document structure:</p>
  
  <pre><code>{
      array_of_subdocs:
           [
               {
                   animal: "cat",
                   count: 10
               },
               {
                   animal: "dog",
                   count: 20
               },
  
               ...
           ]
  }
  </code></pre>
  
  <p>where each document contains an array of sub-documents, I want transform the collection into documents of the structure:</p>
  
  <pre><code>{
      cat: { count: 10 },
      dog: { count: 20 },
      ...
  }
  </code></pre>
  
  <p>where each sub-document is now the value of a new field in the main document named after one of the values within the sub-document (in the example, the values of the <code>animal</code> field is used to create the name of the new fields, i.e. <code>cat</code> and <code>dog</code>).</p>
  
  <p>I know how to do this with <code>eval</code> with a Javascript snippet. It's slow. My question is: how can this be done using the aggregation pipeline?</p>