Skip to content

Instantly share code, notes, and snippets.

@jeremyhaile
Created June 24, 2015 14:05
Show Gist options
  • Save jeremyhaile/f595165dfb641f26a5f1 to your computer and use it in GitHub Desktop.
Save jeremyhaile/f595165dfb641f26a5f1 to your computer and use it in GitHub Desktop.
Build mongo condition hash recursively given a set of ranges and values
def build_agg_hash(condition_hash)
return '' unless condition_hash && condition_hash.length > 0
range, value = condition_hash.shift
{'$cond' => {
'$if' => {'$gte' => range.first, '$lt' => range.last},
'$then' => value,
'$else' => build_agg_hash(condition_hash)
}}
end
build_agg_hash({
(1..10) => 'one',
(11..20) => 'two',
(20..30) => 'three'
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment