title: How can $facet improve $lookup performance
body: <h2>Issue</h2>
  
  <p>I recently attended a tech meetup and showed some of my code to a much more experienced developer. He commented that I would run into issues with my pipeline due to <code>$lookup</code> and that I should consider using <code>$facet</code> to fix this.  </p>
  
  <p>I don't remember what issue he said I would run into nor how <code>$facet</code> could help fix it. I think it has something to do with the 16mb document limit but this can be resolved by using <code>$unwind</code> after <code>$lookup</code>.</p>
  
  <h2>My code (Node.js)</h2>
  
  <p>I have a collection of <code>Post</code> documents. Some posts are <em>parent posts</em>, and other posts are <em>comments</em>. A post that is a comment is identified by the fact that its <code>parent</code> property is NOT <code>null</code>.  </p>
  
  <p>My goal is to return an array of the most recent parent posts and attach to each one, an int property that is the number of comments it has.</p>
  
  <p>Here is my <code>Post</code> mongoose schema</p>
  
  <pre><code>const postSchema = new mongoose.Schema({
      title: { type: String, required: true, trim: true },
      body: { type: String, required: true, trim: true },
      category: { type: String, required: true, trim: true, lowercase: true },
      timestamp: { type: Date, required: true, default: Date.now },
      parent: { type: mongoose.Schema.Types.ObjectId, ref: 'Post', default: null },
  });
  </code></pre>
  
  <p>Here is my pipeline</p>
  
  <pre><code>const pipeline = [
      { $match: { category: query.category } },
      { $sort: { timestamp: -1 } },
      { $skip: (query.page - 1) * query.count },
      { $limit: query.count },
      {
          $lookup: {
              from: 'posts',
              localField: '_id',
              foreignField: 'parent',
              as: 'comments',
          },
      },
      {
          $addFields: {
              comments: { $size: '$comments' },
              id: '$_id',
          },
      },
      { $project: { _id: 0, __v: 0 } },
  ];
  </code></pre>