I have the following method working in ruby. He mainly uses the aggregation structure to select the best trades ordered by the daily quantity sold in active trades with the United States. A deal is a collection in 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]},
daily_quantity: {
"$divide" => [
{"$multiply" => ["$sold_quantity", 3600*24*1000]},
{"$subtract" => [Time.zone.now, "$start_at"]}
]
}
}
}
sort = { "$sort" => { daily_quantity: -1 } }
limit = { "$limit" => k}
collection.aggregate([match, project, sort, limit])
end
I want to change it into scope so that I can combine many scopes for a complex query with flexibility. I just changed the format below:
scope :top_k, lambda { |k|
...
}
Then I got the errors below:
1.9.3-p385 :001 > DS::Deal.top_k(3)
NoMethodError: undefined 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 merge! ' /Users/x/.rvm/gems/ruby-1.9.3-p385/gems/mongoid-3.1.5/lib/mongoid/criteria.rb:77: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 ' (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 ' /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 require ' script/rails: 6: in `'
, , . http://mongoid.org/en/mongoid/docs/querying.html , , , , -.