gpt4 book ai didi

python - 在 mongodb 中查询大列表的最快方法

转载 作者:可可西里 更新时间:2023-11-01 10:03:02 25 4
gpt4 key购买 nike

我想从 mongodb 获取大量用户的详细信息。用户列表超过10万。由于 mongodb 不支持一次性查询非常大的数据。我想知道获取数据的最佳方式。

  1. 分组列表并获取数据

groups_of_list contains list of userId with bunches of 10000

for group in groups_of_list:
curr_data = db.collection.find({'userId': {'$in': group}})
data.append(curr_data)
  1. 遍历集合
for doc in db.collection.find({}):
if i['userId'] in set_of_userIds:
data.append(doc)

我想获得禁食法。

如果有更好的方法/途径,请指出。

最佳答案

恕我直言,您应该像您指出的方法 1 中那样分成“合理大小”的 block ,这不是因为 Mongo 的限制,而是因为您自己机器的内存限制。

大概应该是这样的:

def get_user_slice_data(groups_of_list):
for group in groups_of_list:
yield list(db.collection.find({'userId': {'$in': group}}))

这个生成器函数可以这样使用:

for use_slice_data in get_user_slice_data(groups_of_list):
# do stuff

通过这样做,您既可以避免内存中有大量数据,也可以减少 Mongo 事务的大小。

pd:您可能应该首先考虑在“userId”上添加索引,例如:

db.collection.ensure_index('userId')

关于python - 在 mongodb 中查询大列表的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38523087/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com