use*_*452 5 mongodb mongoid aggregation-framework
我有以下在 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
Run Code Online (Sandbox Code Playgroud)
问题是我想将其更改为范围,以便我可以将许多范围链接在一起,以灵活地进行复杂查询。我只是改成下面的格式:
scope :top_k, lambda { |k|
... # the same method body as uppoer
}
Run Code Online (Sandbox Code Playgroud)
然后我得到以下错误:
1.9.3-p385 :001 > DS::Deal.top_k(3)
Run Code Online (Sandbox Code Playgroud)
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合并!' 来自 /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:intop_k' from (irb):1 from /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:instart' from /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:inrequire' from script/rails:6:in `'
那是因为最后一行返回一个数组,它打破了作用域的要求。从http://mongoid.org/en/mongoid/docs/querying.html看来,我只能为此使用 map reduce,但我想在这里查看是否遗漏了什么。
| 归档时间: |
|
| 查看次数: |
689 次 |
| 最近记录: |