Sort data in Mongo query or array result..?

59 views Asked by At

I'm using mongoose for mongodb queries and lodash orderBy.

Sorting using the mongoose query:

const data = await Products.find(query).sort({ sales: -1 }).lean()

Sorting the result using lodash:

_.orderBy(data, ['sales'], ['desc'])

In general, which is faster..?

1

There are 1 answers

0
Amit Wagner On

well if your sales column is indexed then MongoDB sort will be faster by a lot, as the results are all ready sorted ,

if not i still believe that MongoDB will be faster as it is a DATABASE and i guess they use good sorting algorithms while npm libs not always implement the best algorithm for the task (but maybe lodash does ) and then the results will be the same ,

in conclusion always go for the db option to do staff like that. its safer