$unionWith – MongoDB’s Equivalent of UNION ALL

If you’re familiar with SQL, you might know about the UNION clause, which concatenates the results of two queries into a single result set. In particular, UNION ALL includes duplicates.

In MongoDB, we can use the $unionWith aggregation pipeline stage to achieve the same effect that UNION ALL produces. The $unionWith stage performs a union of two collections – it combines pipeline results from two collections into a single result set. And it includes duplicates.

Continue reading

MongoDB $sortByCount Aggregation Operator

In MongoDB the $sortByCount aggregation pipeline stage groups incoming documents based on the value of a specified expression, then computes the count of documents in each distinct group.

Each group is output in its own document, which consists of two fields:

  • an _id field containing the distinct grouping value, and
  • count field containing the number of documents belonging to that grouping.

The documents are sorted by count in descending order.

Continue reading