title: MongoDB purposely return only users that have no matching $lookup results
body: <p>I have a <code>users</code> schema and a <code>votes</code> schema. I'm trying to return only users who haven't voted (have no returned votes).</p>
  <p>I found <a href="https://stackoverflow.com/a/45438272/3554127">this answer</a> and using <a href="https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/" rel="nofollow noreferrer">$lookup</a> I have the below code to find each user and return all their votes as well. Which is halfway to what I'm trying to achieve.</p>
  <p>How would I build a query so it only returns a user if they have no votes?</p>
  <pre><code>db.users.aggregate([
      { 
          $addFields: { &quot;_id&quot;: { &quot;$toString&quot;: &quot;$_id&quot; } }
      },
     {
       $lookup:
         {
           from: &quot;votes&quot;,
           localField: &quot;_id&quot;,
           foreignField: &quot;voterId&quot;,
           as: &quot;votes&quot;
         }
    }
  ])
  </code></pre>
  <p>Another question once I have a working solution, how would I go about scaling this up? Running this query in Robo 3T takes 9.05 seconds already for just loading 50 users and I have almost 40,000 users and over 200,000 votes in my database (which will only grow). Is there a more efficient way to do this? The final code will run on a Node.js server.</p>
  <h2>Update</h2>
  <p>As <a href="https://stackoverflow.com/users/9040866/silencedogood">silencedogood</a> said in a deleted answer, I don't need to use <code>$addFields</code> because <code>user._id</code> is automatically converted to a string (I thought it would be an <code>ObjectId()</code> initially). This however only saves 1 second off of loading 50 users (8.14s).</p>
  <pre><code>db.users.aggregate([
     {
       $lookup:
         {
           from: &quot;votes&quot;,
           localField: &quot;_id&quot;,
           foreignField: &quot;voterId&quot;,
           as: &quot;votes&quot;
         }
    }
  ])
  </code></pre>
  <p>I still need to figure out how to only return users who <strong>haven't</strong> voted.</p>