Reputation: 3153
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
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"
}
}
}
}
])
Upvotes: 0
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