我在mongoid上使用rails 3.
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的股票,然后能够对每只股票的价格进行排序.
但看起来Mongodb不允许这样做.
@stocks = Stock.Where(:prices.value.lt => p)
此外,mongoDB似乎无法对嵌入对象进行排序.
那么,为了完成这项任务,有没有替代方案?
也许我应该把所有的东西都放在一个集合中,这样我就可以轻松地运行以下查询:
@stocks = Stock.Where(:prices.lt => p)
但我真的希望在查询后得到按股票名称分组的结果(例如,带有一系列有序价格的不同股票).我听说过map/reduce与group函数一起使用,但我不确定如何在Mongoid中正确使用它.
http://www.mongodb.org/display/DOCS/Aggregation
SQL中的类似功能如下所示:
SELECT name, code, min(price) from Stock WHERE price<p GROUP BY name, code
谢谢你的帮助.