查询 Mongoid/rails 3 中的嵌入对象(“低于"、Min 运算符和排序) [英] Querying embedded objects in Mongoid/rails 3 ("Lower than", Min operators and sorting)

查看:14
本文介绍了查询 Mongoid/rails 3 中的嵌入对象(“低于"、Min 运算符和排序)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有 mongoid 的 rails 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)

但我真的想在查询后获得按股票名称分组的结果(例如,具有一系列有序价格的不同股票).我听说过使用 group 功能的 map/reduce,但我不确定如何正确使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆