title: How to query Child elements on MongoDB
body: <p>it's quite looklike with <a href="https://stackoverflow.com/questions/4762947/how-to-query-child-objects-in-mongodb">how to query child objects in mongodb</a></p>
  
  <p>I Have:</p>
  
  <p><img src="https://i.stack.imgur.com/qF4Du.png"></p>
  
  <p>Pais (Country) with its children (ufds(27) on total), I'm making a Ruby seed.rb file to bulky insert from a file.</p>
  
  <p>the mapping files are:</p>
  
  <pre><code>class Pais
    include Mongoid::Document
    field :nome, :type =&gt; String
    field :sigla, :type =&gt; String
  
    embeds_many :ufds
    validates_uniqueness_of :sigla
  end
  
  class Ufd
    include Mongoid::Document
    field :codigo_ibge, :type =&gt; String
    field :sigla, :type =&gt; String
    field :nome, :type =&gt; String
  
    embedded_in :pais, :inverse_of =&gt; :ufds
    embeds_many :cidades
  
    validates_uniqueness_of :codigo_ibge, :sigla
  end
  
  class Cidade
    include Mongoid::Document
    field :codigo_ibge, :type =&gt; String
    field :nome, :type =&gt; String
  
    embedded_in :ufd, :inverse_of =&gt; :cidades
    validates_uniqueness_of :codigo_ibge
  end
  </code></pre>
  
  <p>So when importing, I do beside other things the following:</p>
  
  <pre><code>pais_base = Pais.create!(:nome =&gt; "Brasil", :sigla =&gt; "BR")
  
  File.open(caminho + 'estados.txt').each_with_index do |linha, index|
    sigla, nome, ibge = linha.chomp.split("|")
    pais_base.ufds &lt;&lt; Ufd.new(:sigla =&gt; sigla, :nome =&gt; nome, :codigo_ibge =&gt; ibge )
  end
  </code></pre>
  
  <p>which creates correctly the PAIS and its UFDS children, but now to create a children of UFDS, I load another file and try to find a UFDS with id (codigo_ibge), but always returns null</p>
  
  <pre><code>File.open(caminho + 'cidades.txt').each_with_index do |linha, index|
    ufd, ibge, nome = linha.chomp.split("|")
    uf = pais_base.ufds.find(:first, :conditions =&gt; {:codigo_ibge =&gt; ufd.to_s }) &lt;&lt;&lt;&lt;&lt; NIL
    uf.cidades &lt;&lt; Cidade.new(:codigo_ibge =&gt; ibge.to_s, :nome =&gt; nome)
  end
  </code></pre>
  
  <p>How should I do that? I've run out of ideas :/</p>
  
  <p>Thanks in advance.</p>