title: In MongoDB how do you index an embedded object fields in an array?
body: <p>The mongodb documentation for multikeys gives an example of querying embedded object fields in an array:</p>
  
  <p><a href="http://www.mongodb.org/display/DOCS/Multikeys" rel="noreferrer">http://www.mongodb.org/display/DOCS/Multikeys</a></p>
  
  <p>But there's no explanation on how you create an index for that situation. Creating an index on the array doesn't seem to work (using the explain mechanism you can see the index isn't use).</p>
  
  <p>Additional details:</p>
  
  <pre class="lang-js prettyprint-override"><code>&gt; // find posts where julie commented
  &gt; db.posts.find( { "comments.author" : "julie" } )
  {"title" : "How the west was won", 
   "comments" : [{"text" : "great!" , "author" : "sam"},
                 {"text" : "ok" , "author" : "julie"}],
   "_id" : "497ce79f1ca9ca6d3efca325"}
  </code></pre>
  
  <p>If you do <code>db.articles.ensureIndex( { comments : 1 } )</code> it won't index the subfields of the comments objects but rather only the comments object itself.</p>
  
  <p>So the following would use the index:</p>
  
  <pre><code> &gt; db.posts.find( {comments : { "author" : "julie", "text" : "ok" } } )
  </code></pre>
  
  <p>Because it's search on the comments objects</p>
  
  <p>But the following wouldn't use the index:</p>
  
  <pre><code> &gt; db.posts.find( { "comments.author" : "julie" } )
  </code></pre>
  
  <p>So how do you get mongodb to index for the second case?</p>