Last active
August 29, 2015 14:18
-
-
Save liushooter/46e4be23750ba38db19a to your computer and use it in GitHub Desktop.
mongoid 如何 使用 mongoDB aggregate功能 💋
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class User | |
include Mongoid::Document | |
include Mongoid::Timestamps | |
def self.added_fans(day_num) | |
self.collection.aggregate( | |
{ | |
"$match" => { | |
"followable_type" => "User", | |
"created_at" => { | |
"$gte" => yesterday.to_i.days.ago.beginning_of_day, # 大于等于 昨天的开始时间 | |
"$lte" => Date.yesterday.end_of_day # 小于等于 昨天的结束的时间 | |
} | |
} | |
}, # 查询条件 | |
{ | |
"$group" => { | |
_id: "$follow_id", # 根据 follow_id 分组统计 | |
matches: { "$sum" => 1 } # 统计数量 | |
} | |
}, | |
{ | |
"$sort" => { matches: -1 } #倒序 | |
}, | |
{ | |
"$limit" => 10 | |
} | |
) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment