title: Find duplicate key in embedded sub document in mongodb
body: <p>I am trying to craft a query that will allow me to find <strong>duplicate</strong> keys in <em>subdocument</em> in MongoDB.</p>
  
  <p>It needs to be able to query any number of documents and see what keys are duplicated across them in a subdocument.  The key of my subdocument is called <code>attributes</code> and I need to be able to target a particular query of documents and pull out duplicate attribute keys that they all share.</p>
  
  <p><strong>EDIT:</strong>
  I forgot to mention that I do not know the names of the attributes ahead of time.  I need to be able to essentially select distinct attributes that they share and aggregate the values.</p>
  
  <p>Collection Sample: </p>
  
  
  
  <pre class="lang-js prettyprint-override"><code>[
      {
          sku: '123',
          attributes: {
              size: 'L',
              custom: 7
          }
      },
      {
          sku: '456',
          attributes: {
              size: 'M'
          }
      },
      {
          sku: 'abc',
          attributes: {
              material: 'cotton'
              size: 'S'
          }
      }
  ]
  </code></pre>
  
  <p>Desired Result (if possible):</p>
  
  <pre class="lang-js prettyprint-override"><code>{
     size: [' S', 'M', 'L']
  }
  </code></pre>
  
  <p>If the desired result is not possible I would at least like to be able to get back <code>[ 'size' ]</code></p>
  
  <p>This process needs to be optimized as much as possible and I just cant seem to get a query just right to return what I need, any help is greatly appreciated =)</p>
  
  <p>Here is what I have so far</p>
  
  <pre class="lang-js prettyprint-override"><code>db.getCollection('myCollection').aggregate([
      { $match: {
              _id: { $in: [ObjectId("55158b0bd6076278295cf022"), ObjectId("55158b0bd6076278295cf021"), ObjectId("55158b0bd6076278295cf01f")   ] }
          }
      },
      { $project: { attributes: 1 }},
      { $group: { _id: '$attributes' } }
  
  ])
  </code></pre>
  
  <p>Which products this output:</p>
  
  <pre class="lang-js prettyprint-override"><code>{
      "result" : [ 
          {
              "_id" : {
                  "shirt_size" : "S",
                  "shirt_color" : "Blue",
                  "custom_attr" : "adsfasdf"
              }
          }, 
          {
              "_id" : {
                  "shirt_size" : "M",
                  "shirt_color" : "Green"
              }
          }, 
          {
              "_id" : {
                  "shirt_size" : "L",
                  "shirt_color" : "Red"
              }
          }
      ],
      "ok" : 1.0000000000000000,
      "$gleStats" : {
          "lastOpTime" : Timestamp(1427475045, 1),
          "electionId" : ObjectId("54f7c1edf8e5ff44cec194b6")
      }
  }
  </code></pre>
  
  <p>I feel like it is close and I am just missing the last step :(</p>