Skip to content

Instantly share code, notes, and snippets.

@liushooter
Last active August 29, 2015 14:18
Show Gist options
  • Save liushooter/46e4be23750ba38db19a to your computer and use it in GitHub Desktop.
Save liushooter/46e4be23750ba38db19a to your computer and use it in GitHub Desktop.
mongoid 如何 使用 mongoDB aggregate功能 💋
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