You need to enable JavaScript to run this app. pymongo聚合查询返回CommandCursor无法按下标取值问题
优惠活动
大模型
产品
解决方案
定价
更多

pymongo聚合查询返回CommandCursor无法按下标取值问题

问题原因
  • pymongo的aggregate()方法返回的是CommandCursor迭代器对象,本身不支持下标[0]直接访问
  • 你调用dumps(results)时已经完整遍历消耗了这个迭代器,后续再操作这个变量已经没有剩余数据了
  • 额外注意:pymongo返回的查询结果是字典类型,不能用.属性的方式读取字段,需要用['字段名']的格式访问
修正后可运行代码
import pymongo
from bson.json_util import dumps

client = pymongo.MongoClient('URL')
cursor = client['analytics']['metrics'].aggregate([
    {
        '$match': {
            'name': 'metricName'
        }
    }, {
        '$group': {
            '_id': '$data.location', 
            'Count': {
                '$sum': 1
            }
        }
    }, {
        '$group': {
            '_id': 'metricName', 
            'data': {
                '$addToSet': {
                    'location': '$_id', 
                    'count': '$Count'
                }
            }
        }
    }
])

# 先把迭代器转成列表,后续可以多次操作
results = list(cursor)
print(dumps(results, indent=4, sort_keys=True))

# 取第一个元素
result = results[0]
print(result)

# 遍历获取位置和计数
for item in result['data']:
    print(f"位置:{item['location']},计数:{item['count']}")
简化方案(直接获得位置计数列表,无需多余分组)

如果你的最终需求只是拿到位置和对应计数的列表,可以直接去掉第二个$group步骤,简化代码如下:

import pymongo

client = pymongo.MongoClient('URL')
cursor = client['analytics']['metrics'].aggregate([
    {
        '$match': {
            'name': 'metricName'
        }
    }, {
        '$group': {
            '_id': '$data.location', 
            'count': {
                '$sum': 1
            }
        }
    }
])
# 直接生成你需要的列表格式
location_count_list = [{'location': item['_id'], 'count': item['count']} for item in cursor]
print(location_count_list)

内容的提问来源于stack exchange,提问作者Tim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 15:18:02