我有以下方法在ruby中工作。基本上,它使用聚合框架来选择按活跃美国交易中每日销售数量排序的前k交易。 Deal是MongoDB中的一个集合。
def top_daily_quantity(k)
match = { "$match" =>
{
country: "US",
active: true
}
}
project = {
"$project" => {
_id: 1,
sold_quantity: 1,
days: {"$divide" => [{"$subtract" => [Time.zone.now, "$start_at"]}, 3600*24*1000]}, #note days is in float
daily_quantity: {
"$divide" => [
{"$multiply" => ["$sold_quantity", 3600*24*1000]},
{"$subtract" => [Time.zone.now, "$start_at"]} # this difference is in ms
]
}
}
}
sort = { "$sort" => { daily_quantity: -1 } }
limit = { "$limit" => k}
collection.aggregate([match, project, sort, limit])
end
问题是我想将其更改为范围,以便我可以将多个范围链接在一起,以便灵活地进行复杂查询。我只是改为以下格式:
scope :top_k, lambda { |k|
... # the same method body as uppoer
}
然后我得到了以下错误:
1.9.3-p385 :001 > DS::Deal.top_k(3)
NoMethodError:未定义的方法to_criteria' for #<Array:0x007fb96f35e3c0>
from /Users/x/.rvm/gems/ruby-1.9.3-p385/gems/mongoid-3.1.5/lib/mongoid/criteria.rb:292:in
合并!&#39;
来自/Users/x/.rvm/gems/ruby-1.9.3-p385/gems/mongoid-3.1.5/lib/mongoid/criteria.rb:277:in merge'
from /Users/x/.rvm/gems/ruby-1.9.3-p385/gems/mongoid-3.1.5/lib/mongoid/scoping.rb:305:in
top_k&#39;
来自(irb):1
来自/Users/x/.rvm/gems/ruby-1.9.3-p385/gems/railties-3.2.14/lib/rails/commands/console.rb:47:in start'
from /Users/x/.rvm/gems/ruby-1.9.3-p385/gems/railties-3.2.14/lib/rails/commands/console.rb:8:in
start&#39;
来自/Users/x/.rvm/gems/ruby-1.9.3-p385/gems/railties-3.2.14/lib/rails/commands.rb:41:in <top (required)>'
from script/rails:6:in
要求&#39;
来自script / rails:6:在`&#39;
那是因为最后一行返回了一个打破范围要求的数组。从http://mongoid.org/en/mongoid/docs/querying.html开始,我似乎只能使用map reduce来实现此目的,但我想在这里查看是否遗漏了任何内容。