title: Counting sub-document matches in a mongo document
body: <p>I have a failry simple structure for my documents:</p>
  
  <pre><code>{regId: 1, data: {[{val: 123456}, {val: 324234}, {val: 4353453}, .......]}}
  </code></pre>
  
  <p>The data element array may contain between 30 and 60 sub-documents and currently the collection has ~53000 documents, but will grow much larger.</p>
  
  <p>Given an array of vals, INPUT, [11563012,11563011,82867218,83866648, ....], 
  I want to return documents that have at least 3 matching data.val.  Currently, I query using an $in modifier and a $where clause that calls a js 
  function  (countMatches).  The $in modifier returns any document that contains at least one item for IMPUT and the $where function iterates through each document.date, counting matches in INPUT and only returns documents above the threshold:</p>
  
  <pre><code>db.foo.find({"data.val": {$in: [11563012,11563011,82867218,83866648,.......]}, $where: "countMatches(this.data, [11563012,11563011,82867218,83866648,......])&gt;=3"}).count();
  </code></pre>
  
  <p>Similar questions (http://groups.google.com/group/mongodb-user/browse_thread/thread/fa291575fd47c010) seem to indicate that the only way to count matchs in "sub-documents" is 
  either with a js function in a $where clause or with a group() aggregate function.  </p>
  
  <p>My question then is, is there a better method for counting "hits" in a sub-document?  This is semantically similar to finding "tagged" documents, i.e. return the documents that have the most matching tags of [tag1, tag2, tag3, tag4,.....]</p>