Remove Duplicates when using $unionWith in MongoDB

In MongoDB, the $unionWith aggregation pipeline stage performs a union of two collections, and it includes duplicates.

This behaves in a similar way to SQL’s UNION ALL, which also includes duplicates. By contrast, using just UNION (i.e. without the ALL)in SQL removes duplicates.

In MongoDB, we don’t have the option of specifying $unionWith ALL or similar, so we need to reduce duplicates in another way.

In MongoDB, we can remove duplicates by using the $group stage.

Read more

3 Ways to Sort Documents in MongoDB

MongoDB provides a few ways to sort documents in a particular order. Each of these allow us to order the documents in ascending or descending order.

There’s also the option to order the results of a $text search – sorting by the computed textScore metadata in descending order.

Here are 3 ways to sort documents in MongoDB.

Read more