PyMongo-两个字段中包含的不同值的计数

问题描述 投票:0回答:1

我需要获取以字段“ to”和“ from”中包含的字符串“ hx”开头的不同值的计数。这是我目前的做法:

addresses_from = collection.find({"from": {'$regex':'^hx'}}).distinct("from")
addresses_to = collection.find({"to": {'$regex':'^hx'}}).distinct("to")

unique = set(addresses_from + addresses_to)
count = len(unique)

但是,我已经达到了MongoDB的限制:

pymongo.errors.OperationFailure: distinct too big, 16mb cap

因此需要将其重新做为更好的解决方案,理想情况下,我将直接从MongoDB获取“计数”,而无需在Python中进行进一步处理。

有人可以帮助找到解决方案吗?预先谢谢!

python-3.x mongodb pymongo
1个回答
0
投票

使用distinct() collection level operation:

addresses_from = collection.distinct('from', {'from': {'$regex':'^hx'}})
© www.soinside.com 2019 - 2024. All rights reserved.