Home > other >  How to Optimize a MongoDB Query?
How to Optimize a MongoDB Query?

Time:05-02

i have this query to MongoDB

const getTopUserPosition = async (id, skip = 0, name) => { 
    /* 
    Here I get 1,000 IDis of users in descending balance
   */
    const users = await (await User.find({ admin: 0 }, { id: true, _id: false, }).skip(skip).limit(1_000).sort({
        [`${name}`]: -1
    })).map(x => x.id) /* Array of objects [ { id: 222856843 } ] to  [ 222856843 ] */

    if (!users.length) return 0 /* If havent array length i returning 0 */
    /* If i dont found user id i call this function  again. */
    if (!users.includes(id) || users.indexOf(id) < 0) return getTopUserPosition(id, skip   1_000, name) 
    
    const userPosition = users.indexOf(id)   1

    return userPosition   skip
},

How can i optimize this query? I'm now getting a response from Mongodb within 10 seconds

CodePudding user response:

An alternative way to get the user position in your collection (if all fields have an index) is to count how many documents there are before your document.

const user = await User.find({id: id});
const userPosition = await User.find({"$gt": user[name]}).sort({name: -1}).count();
  • Related