Find all unique values from array of strings across mongo documents

44 Views Asked by At

In a mongo collection, I want to collect all unqiue values from an array of strings. The documentation tells me the $reduce function is the way to go, but I don't see my mistake.

{
  _id: 1,
  values: ['1','2','4']
},
{
  _id: 2,
  values: ['1','3','5']
}

The desired output is a simple array of ['1','2','3','4','5'] where all strings are unique.

My attempt (I am trying to do this in nodeJS):

db.collection
      .aggregate([
        {
          $project: {
            'values': {
              $reduce: {
                input: '$values',
                initialValue: [],
                in: { $concatArrays: ['$$value', '$$this'] }
              }
            }
          }
        }
      ])

Error:

$concatArrays only supports arrays, not string

For details see playground

1

There are 1 best solutions below

0
facebook-100001358991487 On

Try with $unwind and $group something like below

db.getCollection("test").aggregate([{$unwind: "$values"}, {$group: {_id: null, uniqueArray: {$addToSet: "$values"}}}, {$project: {"uniqueArray":1, _id: 0}}])