class Employee
include Mongoid::Document
include Mongoid::Timestamps
STATUSES = ["pending", "approved", "pending_approval", "rejected"]
field :status, type: String, default: "pending"
belongs_to :department
end
class Department
include Mongoid::Document
include Mongoid::Timestamps
DEPARTMENTS = ["it", "account", "business", "marketing"]
field :name, type: String
has_many :employees
end
有 Employee 和 Department 两种模型
我需要获取员工的部门和状态计数以及状态计数总数。
[
# department wise count
{department_id: 1, pending_count: 5, approved_count: 3, pending_approval_count: 3, rejected: 1},
{department_id: 2, pending_count: 2, approved_count: 1, pending_approval_count: 5, rejected: 1},
{department_id: 3, pending_count: 4, approved_count: 2, pending_approval_count: 1, rejected: 2},
{department_id: 4, pending_count: 1, approved_count: 3, pending_approval_count: 1, rejected: 1},
#Total count of above counts
{total_pending_count: 12, total_approved_count: 9, total_pending_approval_count: 10, total_rejected: 5},
]
就像我需要的这种类型的数据。
知道这里需要使用什么聚合查询吗?