D
D
DeFaNJI2021-12-25 00:08:48
JavaScript
DeFaNJI, 2021-12-25 00:08:48

Is it possible to speed up the top compilation function?

I created a function that sorts users by decreasing value in the field, and also looks for the position of a person in the top.

const getTop = async (name, userId) => {
    const top = await Users.find({ admin: false }, { [name]: 1, id: 1 }).sort({
        [`${name}`]: -1,
    });

    let userPosition = 0;

    for (let i = 0; i < top.length; i++) {
        const { id } = top[i];

        if (id === userId) {
            userPosition = i;
            break;
        }
    }

    const topUsers = top.slice(0, 10);

    return [topUsers, userPosition + 1];
}


Is it possible to change it so that it works faster? It seems to me that with a large number of people, the top will be compiled for a large amount of time.

I immediately say that I was looking on the Internet for how to find out the document number when sorting, but I did not find any information about this

Answer the question

In order to leave comments, you need to log in

3 answer(s)
K
kapp1, 2021-12-26
@DeFaNJI

I will try to be less toxic and not write about 10+ years of experience)
You need to read articles or videos about high performance in mongo or optimize query performance.
In short, do not inflate the collection with unnecessary data and make indexes.

A
Alexey Dubrovin, 2021-12-25
@alekcena

About the optimization.

sorts users by decreasing value in the field, as well as

I would think about code splitting, not speed.
Now you are thinking about how to optimize. Not how. You don't know enough about the language to do this.
When you really will "Affect the speed." Then you start thinking.
I immediately say that I was looking on the Internet for how to find out the document number when sorting, but I did not find any information about this

This information is what it is all about.
What document, what sorting?

S
sasmoney, 2021-12-25
@sasmoney

limit the number and split into separate pages to get 1001 rows, 2001, etc.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question