如何在PyMongo中实现排除指定字符串列表的大小写不敏感查询
修正PyMongo查询:排除包含指定子串(大小写不敏感)的文档
错误原因
原代码的问题在于:你试图把字符串".*"、".*/i"和re.compile()返回的**正则对象(re.Pattern)**拼接,Python不允许字符串与正则对象直接相加,因此抛出TypeError。
两种修正方案
方案1:使用MongoDB原生正则语法
直接构造MongoDB支持的正则查询格式,通过$options: "i"实现大小写不敏感:
import pymongo exclude_file_name_substr = ["system", "screenshot"] # 为每个排除子串生成匹配规则,.*匹配任意前后内容 query = {} if exclude_file_name_substr: query["file_name"] = { "$nin": [ {"$regex": f".*{substr}.*", "$options": "i"} for substr in exclude_file_name_substr ] } # 执行查询示例 client = pymongo.MongoClient("mongodb://localhost:27017/") db = client["你的数据库名"] collection = db["你的集合名"] results = collection.find(query)
方案2:使用Python正则对象(带忽略大小写标志)
用re.compile生成正则对象时传入re.IGNORECASE(或简写re.I),PyMongo会自动转换为MongoDB可识别的查询条件:
import pymongo import re exclude_file_name_substr = ["system", "screenshot"] # 生成带大小写不敏感标志的正则对象,.*匹配任意前后内容 regex_list = [ re.compile(f".*{substr}.*", re.IGNORECASE) for substr in exclude_file_name_substr ] query = {} if regex_list: query["file_name"] = {"$nin": regex_list} # 执行查询示例 client = pymongo.MongoClient("mongodb://localhost:27017/") db = client["你的数据库名"] collection = db["你的集合名"] results = collection.find(query)
效果说明
两种方案都能排除所有file_name字段包含"system"或"screenshot"(不区分大小写,比如System_info.png、SCREENSHOT_2024.png)的文档,仅返回不包含这些子串的文档。
内容的提问来源于stack exchange,提问作者SrTan
相关产品推荐
相关产品推荐

