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
Try with
$unwindand$groupsomething like belowdb.getCollection("test").aggregate([{$unwind: "$values"}, {$group: {_id: null, uniqueArray: {$addToSet: "$values"}}}, {$project: {"uniqueArray":1, _id: 0}}])