Skip to content

Instantly share code, notes, and snippets.

@jonstorer
Last active January 3, 2016 06:49
Show Gist options
  • Save jonstorer/8425515 to your computer and use it in GitHub Desktop.
Save jonstorer/8425515 to your computer and use it in GitHub Desktop.
make this one query
# I need to query a doc like this
Info.where(:q_id => 1, :quality.gte =>2).map(:member_id)
# => [123, 124]
Info.where(:q_id => 2, :quality.gte => 1).map(:member_id)
# => [123, 125]
# I need the member ids that are in the result set of both queries
# =>[123]
db.infos = [
{ question_id: 'q1', quality: 2, member_id: 123 },
{ question_id: 'q1', quality: 1, member_id: 124 },
{ question_id: 'q1', quality: 2, member_id: 126 },
{ question_id: 'q2', quality: 1, member_id: 123 },
{ question_id: 'q2', quality: 1, member_id: 127 }
]
# find all member ids who answered:
# question q1 with a min quality of 2
# AND question q2 with a m in quality of 1
requirements = { 'q1' => 2, 'q2' => 1 }
# ids = requirements.inject([]) do |member_ids, question_id, quality|
# ids = Info.where(:question_id => question_id, :quality => { '$gte' => quality }).only(:member_id).map(&:member_id)
# if member_ids.empty?
# member_ids = ids
# else
# member_ids & ids
# end
# end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment