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.

Continue reading

How to Format the Date in MongoDB

If you have documents that store dates as Date objects, but you want to return them in a different format, you can use the $dateToString aggregate pipeline operator.

For example, you might want a date to be returned in mm/dd/yyyy format instead of the long ISODate() format that includes minutes, seconds, milliseconds, etc

The $dateToString operator converts the Date object to a string, and optionally allows you to specify a format for the resulting output.

Continue reading