iLiA
iLiA

Reputation: 3153

add up every array's length inside result

so i am trying to get distinct array values in mongoose like this

await Model.distinct('array');

and my aim is to get every array and add up their lengths, it could be easily done with for loop like so

for(const val of array){
    sum += array.length
};

but I really want to not use for loop, so is there any way to implement such thing with O(1) ?

Upvotes: 0

Views: 31

Answers (2)

Valijon
Valijon

Reputation: 13103

You may use native MongoDB solution ($group + sum array size). It's up x2 faster than a regular for loop

await Model.aggregate([
  {
    $group: {
      _id: "$array"
    }
  },
  {
    $group: {
      _id: null,
      sum: {
        $sum: {
          $size: "$_id"
        }
      }
    }
  }
])

MongoPlayground

Upvotes: 0

Ryker
Ryker

Reputation: 802

You can use aggregate query for performing the opertaion.

const sum = await Model.aggregate(
  {
    $group: {
      _id: '$array'
    }
  },
  {
    $unwind: {
       path: '$_id'
    }
  },
  {
    $project: {
      total_length: { $sum: '$_id'}
    }
  }
)

Though the operation will not be O(1) but will be significantly faster as well as use very less memory.

Upvotes: 1

Related Questions