Mongo query to count no. of questions and votes by different gender with their total sum.
group_by = if @filter[:by] == ‘geolocation’
({ “country_code”: “$country_code”, “state_code”: “$state_code” })
else
({ “day”: {“$dayOfMonth”: “$created_at”}, “month”: {“$month”: “$created_at”}, “year”: {“$year”: “$created_at”} })
end
data = Question.collection.aggregate([
{ “$match”:
{
“asked_to”: @filter[:loggedin_user_id],
“created_at”: { “$gte”: filter[:from_date], “$lt”: filter[:to_date] }
}
},
{ “$group”:
{ “_id”: group_by,
“male”: {“$sum”:{“$cond”:[{“$eq”:[“$asker_gender”, “male”]},1,0]} },
“female”: {“$sum”:{“$cond”:[{“$eq”:[“$asker_gender”, “female”]},1,0]}},
“other”: {“$sum”:{“$cond”:[{“$eq”:[“$asker_gender”, “other”]},1,0]}},
“total”: {“$sum”:1},
“male_votes”: {“$sum”: {“$cond”: [ { “$gte”: [ “$asker_gender”, “male” ] }, “$requestor_count”, 0 ]}},
“female_votes”: {“$sum”: {“$cond”: [ { “$gte”: [ “$asker_gender”, “female” ] }, “$requestor_count”, 0 ]}},
“other_votes”: {“$sum”: {“$cond”: [ { “$gte”: [ “$asker_gender”, “other” ] }, “$requestor_count”, 0 ]}},
“total_votes”: {“$sum”: “$requestor_count”}
}
}
])