我對 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 的回應
uj5u.com熱心網友回復:
獲取用戶在集合中的位置(如果所有欄位都有索引)的另一種方法是計算檔案之前有多少檔案。
const user = await User.find({id: id});
const userPosition = await User.find({"$gt": user[name]}).sort({name: -1}).count();
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/470262.html