当数据非常嵌套时,如何使用$gt和aggregate Pymongo聚合文档

2024-04-24 19:50:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我将我的数据放在一个集合collec中,然后数据是嵌套的。我想获取我的db中的所有数据,它有一个confidence> 0.33

我写了一个如下的查询:

returned_data = {}
for q in collec.find({"question": {"$in":all_question_ids}})):
    if q['response']['detection']['confidence'] >= 0.3:
        returned_data[q['id1']] = q['response']['detection']['confidence']

这花费了太多的时间,我认为这是在逐个查找每个条目

如何使用aggregate$gt来获得结果


1条回答
网友
1楼 · 发布于 2024-04-24 19:50:53

您可以使用聚合查询来使用管道(即一系列操作)提取相关数据。首先,您将基于大于0.3的置信度匹配文档,然后您可以投影匹配的文档,以便只返回必需的字段

pipeline = [
    {'$match': {'response.detection.confidence': {'$gt': 0.3}}},
    {'$project': {'question_id': '$id1',
                  'confidence': '$response.detection.confidence'}
    ]

cursor = collec.aggregate(pipeline, useCursor=True, batchSize=50000) 
result = list(cursor)

相关问题 更多 >