Mongo query with aggregate function for rails


Group by state and created at:

   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”} 
          }
        }
      ])

About the author

Being the CEO and Founder of ClecoTech International, Mr. Ashish Prajapati is dedicated towards his aim of mentoring young startups into a full-fledged businesses. He is helping startups from America, Europe, India, and various other countries through proper guidance and the use of latest technologies to develop their innovation and ideas into definite realities.

Leave a Reply

Your email address will not be published.