skip to Main Content
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


  1. You don’t need $reduce. Simply use

    {
       $set: { items: { $setUnion: "$myInputFromPreviousGroupAction" } }
    }
    

    You can also use $size

    {
       $set: { items: { $size: { $setUnion: "$myInputFromPreviousGroupAction" } } }
    }
    
    Login or Signup to reply.
  2. you can calculate the count of elements directly within the $addFields stage using the $size operator and the $reduce expression.

    Exercise.aggregate([
       { $match: {} },
       {
          $group: {
             _id: '$userId',
             correct: { $push: '$stats.correctWords' }
          }
       },
       {
          $addFields: {
             correctsCount: {
                $size: {
                   $reduce: {
                      input: '$correct',
                      initialValue: [],
                      in: { $setUnion: ['$$value', '$$this'] }
                   }
                }
             }
          }
       }
    ])
    

    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..

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search