在控制台中玩了很多次之后,我想出了这种方法,可以在它们发生的那一天将类似activerecord的(Mongoid)对象分组.我不确定这是实现这一目标的最佳方式,但它确实有效.有没有人有更好的建议,或者这是一个好方法吗?
#events is an array of activerecord-like objects that include a time attribute
events.map{ |event|
# convert events array into an array of hashes with the day of the month and the event
{ :number => event.time.day, :event => event }
}.reduce({}){ |memo,day|
# convert this into a hash with arrays of events keyed by their day or occurrance
( memo[day[:number]] ||= [] ) << day[:event]
memo
}
=> {
29 => [e1, e2],
28 => [e3, e4, e5],
27 …Run Code Online (Sandbox Code Playgroud) 我想为Mongoid中的分组提供条件,但是如何在条件哈希中为属性发送多个值?这就是我想要做的:
PageViews.collection.group(
cond: {page_id: ['4e6912618083ab383e000010', '4e6912618083ab383e000009']},
key: 'timestamp',
initial: {count: 0},
reduce: "function(x, y) {y.count += x.count;}"
)
Run Code Online (Sandbox Code Playgroud)
所以任何PageView一个都page_id将是查询的一部分,但我似乎无法让条件hash(cond)完全工作!我在这里做错了什么,我真的很困惑.
以下是该group()方法的API文档:http://api.mongodb.org/ruby/current/Mongo/Collection.html#group-instance_method
任何帮助将不胜感激.
更新
像这样运行查询:
PageViews.collection.group(
cond: {page_id: { $in : ['4e6912618083ab383e000010', '4e6912618083ab383e000009']}},
key: 'timestamp',
initial: {count: 0},
reduce: "function(x, y) {y.count += x.count;}"
)
Run Code Online (Sandbox Code Playgroud)
返回以下错误,但语法对我来说很好:
SyntaxError: (irb):170: syntax error, unexpected ':', expecting tASSOC
cond: {page_id: { $in : ['4e6912618083ab383e000010',...
^
(irb):170: syntax error, unexpected '}', expecting $end
...', '4e6912618083ab383e000009']}},
... …Run Code Online (Sandbox Code Playgroud) 我有一个mongo表,其中包含如下统计数据....
which is a string, played or completed所以我的班级如下......
class Statistic
include Mongoid::Document
include Mongoid::Timestamps
include Mongoid::Paranoia
field :course_id, type: Integer
field :status, type: String # currently this is either play or complete
Run Code Online (Sandbox Code Playgroud)
我想每天获得一个课程总数的数量.所以例如... 8/1/12有2个剧本,8/2/12有6个剧本.等等.因此我将使用created_at时间戳字段,使用course_id和action.问题是我没有看到Mongoid中的group by方法.我相信mongodb现在有一个,但我不确定如何在rails 3中完成.
我可以使用每个来运行表格,并在轨道中加入一些地图或散列,但是如果课程有100万个视图,那么检索和迭代超过一百万条记录可能会很麻烦.有干净的方法吗?
ruby-on-rails mongodb mongoid ruby-on-rails-3 ruby-on-rails-3.2