title: Retrieve n random document with certain filters MongoDB
body: <p>I need to retrieve from a collection of random docs based on a limit given.
  If some filters are provided they should be added to filter the results of the response. I'm able to build the match and size based on the fields provided but even tho I have 20 documents that meet the filter when I make the call I receive only 2 or 3 docs back and I can't seem to figure it out. If I set only the limit it does give me back N random docs based on the limit but if I add a filter it won't give me the wanted results.</p>
  
  <p>This is what I do now</p>
  
  <pre><code>const limit = Number(req.query.limit || 1);
  
    const difficulty = req.query.difficulty;
    const category = req.query.category;
    const settings = [
      {
        $sample: {
          size: limit
        }
      }
    ];
  
    if (difficulty &amp;&amp; category) {
      settings.push({
        $match: {
          difficulty: difficulty,
          category: category
        }
      });
    } else if (difficulty &amp;&amp; category == null) {
      settings.push({
        $match: {
          difficulty
        }
      });
    }
  
    if (difficulty == null &amp;&amp; category) {
      settings.push({
        $match: {
          category
        }
      });
    }
    console.log(settings);
  
    Question.aggregate(settings)
      .then(docs =&gt; {
        const response = {
          count: docs.length,
          difficulty: difficulty ? difficulty : "random",
          questions:
            docs.length &gt; 0
              ? docs.map(question =&gt; {
                  return {
                    _id: question._id,
                    question: question.question,
                    answers: question.answers,
                    difficulty: question.difficulty,
                    category: question.category,
                    request: {
                      type: "GET",
                      url:
                        req.protocol +
                        "://" +
                        req.get("host") +
                        "/questions/" +
                        question._id
                    }
                  };
                })
              : {
                  message: "No results found"
                }
        };
  
        res.status(200).json(response);
      })
      .catch(err =&gt; {
        res.status(500).json({
          error: err
        });
      });
  </code></pre>