title: Better Alternative than $all with $elemMatch
body: <p>Here's a sample document of my Mongo DB structure:</p>
  
  <pre><code>{ _id: 1
    records: [{n: "Name", v: "Kevin"}, 
              {n: "Age", v: "100"}, 
               ..., 
              {n: "Field25", v: "Value25"} ]
  }
  </code></pre>
  
  <p>To search on all documents having <code>Name of "Kevin" and an Age of "100"</code>, I'm using <strong>$all</strong> with <strong>$elemMatch</strong>. I need to use $elemMatch's for an exact sub-document match of n: "Name" and v: "Kevin", as well as $all since I'm querying on an <strong>array</strong>.</p>
  
  <pre><code>db.collection.find({"records" : { $all: [
                                           {$elemMatch: {n: "Name", v: "Kevin"},
                                           {$elemMatch: {n: "Age", v: "100"}
                                          ]}})
  </code></pre>
  
  <p>However, the $all operator is inefficient when the first $elemMatch argument is non-selective, i.e. there are many documents that match this field.</p>
  
  <p>The Mongo <a href="http://docs.mongodb.org/manual/reference/operator/query/all/#use-all-with-elemmatch" rel="nofollow">Docs</a> elaborate:</p>
  
  <blockquote>
    <p>In the current release, queries that use the $all operator must scan
    all the documents that match the first element in the query array. As
    a result, even with an index to support the query, the operation may
    be long running, particularly when the first element in the array is
    not very selective.</p>
  </blockquote>
  
  <p>Is there a better alternative for my queries?</p>