Project a counter of occurrences from document array

This is NOT a good way - you should never use $unwind and then $group when you just need to transform a single document!

If you have an array flags: [ 'a', 'b', 'x', 'y', ... ] the way to get number of unique entries is like this:

{$addFields:{
    flags: {$map: {
         input: {$setUnion:"$flags"},  /* unique elements of flags array */
         as: "f", 
         in: {
              name: "$$f",
              count: {$size: {$filter:{input:"$flags", cond:{$eq:["$$this", "$$f"]}}}}
         }
    }}
}}

Asya

3 Likes