构造pymongo搜索字符串时遇OperationFailure错误,求解决方案
解决PyMongo中count_documents的"match filter must be an expression in an object"错误
问题场景
手动编写的PyMongo查询可以正常运行:
number_of_matches = db[collection_selected].count_documents({'color': {'$regex': 'red', '$options': 'i'}, 'usage': {'$regex': 'build', '$options': 'i'}})
为支持用户自定义多个搜索键和匹配模式,编写了函数生成对应的字符串形式的查询条件,示例生成内容:
{'color': {'$regex': 'red', '$options': 'i'}, 'usage': {'$regex': 'build', '$options': 'i'}}
但使用该字符串调用count_documents时触发错误:
pymongo.errors.OperationFailure: the match filter must be an expression in an object, full error: {'ok': 0.0, 'errmsg': 'the match filter must be an expression in an object', 'code': 15959, 'codeName': 'Location15959'}
解决方案
核心原因
count_documents要求传入Python字典对象作为匹配过滤器,而你传入的是字符串类型,MongoDB无法解析字符串格式的查询条件。
修复方式
直接生成字典(推荐)
修改生成查询条件的函数,直接构建Python字典而非字符串:def generate_search_query(search_params): query = {} for field, pattern in search_params.items(): query[field] = {'$regex': pattern, '$options': 'i'} return query # 调用示例 search_params = {'color': 'red', 'usage': 'build'} search_query = generate_search_query(search_params) number_of_matches = db[collection_selected].count_documents(search_query)字符串转字典(仅当无法直接生成字典时使用)
如果必须先生成字符串,使用ast.literal_eval()将字符串安全转换为字典(禁止使用eval(),存在安全风险):import ast # 假设search_string是生成的字符串 search_query = ast.literal_eval(search_string) number_of_matches = db[collection_selected].count_documents(search_query)
内容的提问来源于stack exchange,提问作者Zuly
相关产品推荐
相关产品推荐

