Search code examples
javascriptmongodbmongooseaggregation-framework

Mongo Aggregation: Aggregating Lengths of 2D Array


Hope you are well.

I'm making a quiz feature and storing responses in a 2D array called results, with the index of the subarray corresponding to the index of the answer choice (which has its own array), and the subarray being populated with user IDs who have selected such answer choice.

For example, the answer choices for this quiz may be ["Strawberries", "Apples", "Bananas", "Pineapples"] and the results data may be [["10938381", "10938382"], [], ["10938383", "10938384", "10938385"], ["10938386"]] - indicating 2 responses for Strawberries, 0 for Apples, 3 for Bananas and 1 for Pineapples.

Using the Mongoose JavaScript wrapper for MongoDB, how would I use Mongoose's .aggregate() function to appropriately convert a 2D array into a 1 dimensional array containing the respective lengths of the second dimension?

Input:

{ "results": [["10938381", "10938382"], [], ["10938383", "10938384", "10938385"], ["10938386"]] }

Result:

{ "results": [2, 0, 3, 1] }

The values of the result's array correspond to the input's second-dimension array length, respectively.

Furthermore, I would like to state that the results array may not always have four sub-arrays as the quiz feature may range from 2 to 5 answer choices to choose from.

I apologize if I'm being unclear; if you have questions, please ask.

Thank you very much!


Solution

  • One option is to use $map:

    db.collection.aggregate([
      {$project: {results: {
            $map: {
              input: "$results",
              in: {$size: "$$this"}
            }
      }}}
    ])
    

    See how it works on the playground example