加快 MongoDB 查询响应 |不和谐机器人

Speed up MongoDB Query Response | Discord Bot

我不认为这会是个问题,但随着我使用的数据库不断增长,我注意到我的程序的响应越来越慢(这是有道理的,更多的东西要查看 return).

现在我的问题是我怎样才能加快响应速度,因为现在需要相当长的时间来完成以下操作: 我想对查询搜索的前 10 个结果进行 return 排序,目前,我的代码看起来类似于:

alldocuments = self.bot.db.nameofdb.find()
alldocuments = list(map(lambda x: x["userId"], alldocuments ))
_documentCount = [(i, alldocuments.count(i)) for i in set(alldocuments)]
_documentCount.sort(key = lambda x: x[1], reverse=True)
docCount = list(filter(lambda x: ctx.guild.get_member(int(x[0])), _documentCount))
        
        
i = 0
while i < 10:
     if not ctx.guild.get_member(int(docCount[i][0])):
          i+=1
          continue
     print(docCount[i][1]})
     i += 1

一些信息:

数据库包含以下数千个条目:

Entry Ex. 1:
{
_id: 62338b6994b3773415bd7efc
uid: "849551661"
gacha_type: 100
item_id: ""
count: "1"
time: "2021-12-25 17:42:58"
name: "Magic Guide"
lang: "en-us"
item_type: "Weapon"
rank_type: "3"
id: "1640423160000228061"
userId: 738362958253522976
}

Entry Ex. 2
{

_id: 62338b6994b3773415bd7efe
uid: "849551661"
gacha_type: 100
item_id: ""
count: "1"
time: "2021-12-25 17:42:58"
name: "Noelle"
lang: "en-us"
item_type: "Character"
rank_type: "4"
id: "1640423160000227861"
userId: 738362958253522976

}

现在我的数据库中存在超过 100k 个这样的条目,我想按 userId 对它们进行排序,其中“userId”的条目数量最多。

示例结果应该类似于:

1. 25k - userId
2. 15k - userId
3. 10k - userId
4. 8k - userId
5. 5k - userId
6. 1k - userId
7. 200 - userId
8. 100 - userId
9. 50 - userId
10. 25 - userId

任何少于 25 个条目的人都会被忽略。

使用 MongoDB,您可以直接将您正在应用的那些过滤器包含在您的查询中。这应该会通过加载更少的数据来影响您的运行时间。

documents = self.bot.db.nameofbd.find({"queryparam": True})
sorted_documents = documents.sort("queryparam": pymongo.DESCENDING)

如果没有适当的信息(即可能还有 2-3 个示例输入文档和示例结果),则很难给出答案。但是,可能是这个:

db.collection.aggregate([
  {
    $group: {
      _id: {
        location: "$location",
        name: "$name"
      },
      count: { $sum: 1 }
    }
  },
  { $sort: { count: -1 } },
  { $limit: 10 }
])