查询Mongoid/rails 3中的嵌入式对象(“小于",Min运算符和排序) [英] Querying embedded objects in Mongoid/rails 3 ("Lower than", Min operators and sorting)
问题描述
我正在使用带有蒙古型的滑轨3. 我有一个带有嵌入式价格集合的股票集合:
I am using rails 3 with mongoid. I have a collection of Stocks with an embedded collection of Prices :
class Stock
include Mongoid::Document
field :name, :type => String
field :code, :type => Integer
embeds_many :prices
class Price
include Mongoid::Document
field :date, :type => DateTime
field :value, :type => Float
embedded_in :stock, :inverse_of => :prices
我想获得自给定日期以来的最低价格低于给定价格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.
但是看来Mongodb不允许这样做. 因为这行不通:
But it looks like Mongodb does not allow to do it. Because this will not work:
@stocks = Stock.Where(:prices.value.lt => p)
此外,似乎mongoDB无法对嵌入式对象进行排序.
Also, it seems that mongoDB can not sort embedded objects.
那么,是否有替代方法可以完成此任务?
So, is there an alternative in order to accomplish this task ?
也许我应该将所有内容都放在一个集合中,以便可以轻松运行以下查询:
Maybe i should put everything in one collection so that i could easily run the following query:
@stocks = Stock.Where(:prices.lt => p)
但是我真的很想在查询后得到按股票名称分组的结果(例如,具有一系列定单价格的不同股票).我听说过使用组函数进行映射/归约的情况,但是我不确定如何在Mongoid中正确使用它.
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.
http://www.mongodb.org/display/DOCS/Aggregation
SQL中的等效内容如下:
The equivalent in SQL would be something like this:
SELECT name, code, min(price) from Stock WHERE price<p GROUP BY name, code
感谢您的帮助.
推荐答案
MongoDB/Mongoid允许您执行此操作.您的示例可以使用,语法不正确.
MongoDB / Mongoid do allow you to do this. Your example will work, the syntax is just incorrect.
@stocks = Stock.Where(:prices.value.lt => p) #does not work
@stocks = Stock.where('prices.value' => {'$lt' => p}) #this should work
而且,它仍然可以链接,因此您也可以按名称订购:
And, it's still chainable so you can order by name as well:
@stocks = Stock.where('prices.value' => {'$lt' => p}).asc(:name)
希望这会有所帮助.
这篇关于查询Mongoid/rails 3中的嵌入式对象(“小于",Min运算符和排序)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!