title: Select MongoDB documents with custom random probability distribution
body: <p>I have a collection that looks something like this:</p>
  
  <pre><code>[
    {
      "id": 1,
      "tier": 0
    },
    {
      "id": 2,
      "tier": 1
    },
    {
      "id": 3
      "tier": 2
    },
    {
      "id": 4,
      "tier": 0
    }
  ]
  </code></pre>
  
  <p>Is there a standard way to select <em>n</em> elements where the probabilty of choosing an element of the lowest tier is <em>p</em>, the next lowest tier is (1-<em>p</em>)*<em>p</em>, and so on, with standard random selection of element?</p>
  
  <p>So for example, <strong>if the most likely thing happens</strong> and I run the query against the above example with <em>n</em> = 2 and any <em>p</em> > .5 (which I think will always be true), then I'd get back <code>[{"id": 1, ...}, {"id": 4}]</code>; with <em>n</em> = 3, then <code>[{"id": 4}, {"id": 1}, {"id": 2}]</code>, etc. </p>
  
  <p>E.g. here's some pseudo-Python code given a dictionary like that as <em>objs</em>:</p>
  
  <pre><code>def f(objs, p, n):
    # get eligible tiers
    tiers_set = set()
    for o in objs:
      eligible_tiers.add(o["tier"])
    tiers_list = sorted(list(tiers_set))
    # get the tier for each index of results
    tiers = []
    while len(tiers) &lt; min(n, len(obis)):
      tiers.append(select_random_with_initial_p(eligible_tiers, p))
    # get res
    res = []
    for tier in tiers:
      res.append(select_standard_random_in_tier(objs, tier)
    return res
  </code></pre>