Exercise.aggregate([
{$match: {}},
{
$group: {
_id: '$userId',
correct: {$push: '$stats.correctWords'} // correctWords is array => ['a', 'b', 'c']
}
},
{
$addFields: {
correctItems: {
$reduce: {
input: '$correct',
initialValue: [],
in: { $setUnion: ['$$value', '$$this'] }
}
}
}
},
{
$project: {
correctsCount: {$size: {$ifNull: ['$correctItems', []]}},
}
}
])
some input:
{userId: 'a', stats: {correctWords: ['a', 'b'], ...}}
{userId: 'b', stats: {correctWords: ['a', 'd'], ...}}
{userId: 'a', stats: {correctWords: ['g', 'bc'], ...}}
{userId: 'b', stats: {correctWords: ['a', 'tt'], ...}}
need output:
[{userId: 'a', correctsCount: 4}, {userId: 'b', correctsCount: 3}]
$reduce returns an array of elements, can I somehow immediately calculate them without additional $project ?
2
Answers
You don’t need
$reduce
. Simply useYou can also use
$size
you can calculate the count of elements directly within the $addFields stage using the $size operator and the $reduce expression.
By combining the $size operator and the $reduce expression within $addFields, you can calculate the count of elements without the need for an additional $project stage.
hope it’s helpful..