title: Keep the main document when filtered array is empty in aggregation pipeline
body: <p>This is really an addition to a <a href="https://stackoverflow.com/questions/28788705/subtract-subdocuments-from-collection-in-aggregate-pipeline">previously asked question</a>. With some help from @JohnnyHK I can now remove unwanted subdocuments from an array based on a particular criteria: <code>deleted != null</code>. I discovered that my <code>$unwind</code> pipe broke when there were no items in the array so I also implemented a <code>$cond</code> to add in a dummy object where the array was empty. Here is the code so far:</p>
  
  <pre><code>Collection.aggregate([
          { $match:
              { _id: ObjectID(collection_id) }
          },
          {
            $project:
              {
                _id: 1,
                name: 1,
                images: {
                  $cond:
                    [
                      {
                        $eq:
                          [
                            "$images",
                            []
                          ]
                      },
                      [
                        dummyImg // Variable containing dummy object
                      ],
                      '$images'
                    ]
                },
              }
          },
          { $unwind: "$images" },
          { $match:
              { "images.deleted": null }
          },
  
          // Regroup the docs by _id to reassemble the images array
          {$group: {
              _id: '$_id',
              name: {$first: '$name'},
              images: {$push: '$images'}
          }}
  
      ], function (err, result) {
      if (err) {
          console.log(err);
          return;
      }
      console.log(result);
  });
  </code></pre>
  
  <p>The problem now occurs when the array is not empty but only contains objects where deleted is null. I <code>$unwind</code> the images but the <code>$match</code> doesn't find any matches so can't the perform the final <code>$group</code>.</p>
  
  <p>I'm thinking along the lines of pushing in the dummy object at the beginning of the pipeline and then counting the images towards the end. The dummy object will stay if it is the only one but will need removing if there are other image objects that have made it through the pipeline.</p>
  
  <p>If this is a sensible route I'd be glad of some pointers. If my thinking is way off, any tips to steer me in the right direction will be gratefully received.</p>
  
  <p>Thank you.</p>