title: MongoDB: query array within embedded document
body: <p>I have the following doc definition (it's ruby)</p>
  
  <pre><code>class Block
    include Mongoid::Document
  
    field :index, type: Integer  # index 0,1,..  
    field :codes, type: Array    #[A, B, C,... ]
  
    embedded_in :Video
  end
  
  class Video
    include Mongoid::Document
  
    field :name, type: String
    embeds_many :blocks, :order =&gt; :index.asc
  end
  </code></pre>
  
  <p>I want to query matching the property <code>video.blocks.codes</code>, but it is an array property of an embedded doc. I mainly want to do two types of queries:</p>
  
  <ul>
  <li>How many blocks exist with a non-null/non-empty <code>codes</code> array?</li>
  <li>How many blocks exist where the codes array matches a certain string in a given position?</li>
  </ul>
  
  <p>Here's an example of the data I'm trying to match:</p>
  
  <pre><code>video#1
  blocks: [{index: 1, codes:["a","g","c"]}, {index: 2, codes: [] }]
  
  video#2
  blocks: [{index: 1, codes:["x","b","d", "e"]}, {index: 2, codes: ["x","b"] }]
  </code></pre>
  
  <p>For example, I want to know <em>how many blocks are there without non-empty codes array</em> (answer is <strong>three blocks</strong>), and <em>how many blocks are there with a <code>b</code> in the second position(index 1)</em> (answer is there are <strong>two</strong>).</p>
  
  <p>I'm using the <code>mongoid</code> driver so ideally the query would use the driver, but plain mongo is fine. Thanks!</p>