How to combine all documents’ field of array together in MongoDB?

How to combine the field of the array of all documents together in MongoDB?

For example:

My collection contains these documents:

[
  {
    _id: 0,
    categories: ['a', 'b', 'c'],
  },
  {
    _id: 1,
    categories: ['d', 'e', 'f'],
  },
  {
    _id: 2,
    categories: ['g', 'h', 'i'],
  },
];

And the result must be:

['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']

Answer

Best way to do this is to use distinct

db.collection.distinct('categories')

If the results are more than 16mb then you can only use $unwind and $group in an aggregation:

db.collection.aggregate([
    {
        $unwind: "$categories"
    },
    {
        $group: {
            _id: "$categories"
        }
    }
])