Note that there are some explanatory texts on larger screens.

plurals
  1. POQuerying embedded objects in Mongoid/rails 3 ("Lower than", Min operators and sorting)
    primarykey
    data
    text
    <p>I am using rails 3 with mongoid. I have a collection of Stocks with an embedded collection of Prices :</p> <pre><code>class Stock include Mongoid::Document field :name, :type =&gt; String field :code, :type =&gt; Integer embeds_many :prices class Price include Mongoid::Document field :date, :type =&gt; DateTime field :value, :type =&gt; Float embedded_in :stock, :inverse_of =&gt; :prices </code></pre> <p>I would like to get the stocks whose the minimum price since a given date is lower than a given price p, and then be able to sort the prices for each stock.</p> <p>But it looks like Mongodb does not allow to do it. Because this will not work:</p> <pre><code>@stocks = Stock.Where(:prices.value.lt =&gt; p) </code></pre> <p>Also, it seems that mongoDB can not sort embedded objects.</p> <p>So, is there an alternative in order to accomplish this task ? </p> <p>Maybe i should put everything in one collection so that i could easily run the following query:</p> <pre><code>@stocks = Stock.Where(:prices.lt =&gt; p) </code></pre> <p>But i really want to get results grouped by stock names after my query (distinct stocks with an array of ordered prices for example). I have heard about map/reduce with the group function but i am not sure how to use it correctly with Mongoid.</p> <p><a href="http://www.mongodb.org/display/DOCS/Aggregation" rel="noreferrer">http://www.mongodb.org/display/DOCS/Aggregation</a></p> <p>The equivalent in SQL would be something like this:</p> <pre><code>SELECT name, code, min(price) from Stock WHERE price&lt;p GROUP BY name, code </code></pre> <p>Thanks for your help.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload