如何优化 MongoDB 查询?

How to Optimize a MongoDB Query?

我有这个查询 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
},

我该如何优化这个查询?我现在会在 10 秒内收到 Mongodb 的回复

另一种获取用户在您的集合中的位置(如果所有字段都有索引)的方法是计算您的文档之前有多少文档。

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