MongoDB聚合查询报TypeError: unhashable type: 'dict'问题求助
MongoDB聚合查询报错修复
你遇到的报错是因为聚合管道的语法错误,具体问题和修复方案如下:
原代码问题点
- 第一个聚合阶段不是合法的管道操作:你想检查
Merchant State字段是否存在,但直接写{"Merchent State": {"$exists": "true"}}不符合聚合管道规则,必须包裹在$match操作符内 $match阶段多嵌套了一层大括号:写成$match: {{...}}的形式,导致Python将内层字典识别为外层字典的键,触发unhashable type: 'dict'错误- 字段名拼写错误:
Merchent State应为Merchant State(少写了一个字母a) $exists参数错误:应该传入布尔值True而非字符串"true"
修正后的代码
from pprint import pprint import matplotlib.pyplot as plt import numpy as np import pandas as pd import pymongo as pymongo from pymongo import MongoClient client = MongoClient("localhost", 27017) mydatabase = client.project collection = mydatabase.CS532 results = collection.aggregate([ # 合并查询条件到一个$match阶段,同时过滤非欺诈交易和存在州字段的数据 { "$match": { "Is Fraud?": "No", "Merchant State": {"$exists": True} } }, { "$group": { "_id": "$Merchant State", "count": {"$sum": 1} } }, { "$sort": {"count": -1} }, { "$limit": 3 } ]) for x in results: pprint(x)
关键修正说明
- 聚合管道的每个阶段必须是包含管道操作符(如
$match、$group)的字典,不能直接写查询条件 - 将多个过滤条件合并到同一个
$match阶段,能减少后续聚合处理的数据量,提升效率 - 修正字段名拼写和
$exists参数类型,确保查询和分组逻辑的一致性
内容的提问来源于stack exchange,提问作者Skywalker_229
相关产品推荐
相关产品推荐

