尝试用Pymongo驱动程序创建一个MongoDB查询,该驱动程序搜索数据库以查找一些狗品种,但由于数据质量不同,我需要进行模式匹配。我知道我不能在$in样式的查询中使用Regex,所以我使用JS模式。
到目前为止,我有这样的看法:
df = shelter.getRecords({
"breed": {"$in": [/labrador/i, /chesa/i, /newfound/i]}
})但我有语法错误。命令似乎在shell....is中工作,这是Pymongo的一个限制吗?
发布于 2022-10-06 20:58:00
你可以像这样用"$regex"。
注:您的pymongo查询筛选器可以是python字典,比如{'breed': {'$regex': '(labrador)|(chesa)|(newfound)', '$options': 'i'}}。
db.shelter.find({
"breed": {
"$regex": "(labrador)|(chesa)|(newfound)",
"$options": "i"
}
})示例输出:
[
{
"_id": 21,
"breed": "Chesapeake Retriever"
},
{
"_id": 80,
"breed": "Newfoundland"
}
]在mongoplayground.net上试一试。
发布于 2022-10-12 01:56:07
最后这是我的混合方案..。
labRegex = re.compile(".*lab.*", re.IGNORECASE)
chesaRegex = re.compile(".*chesa.*", re.IGNORECASE)
newRegex = re.compile(".*newf.*", re.IGNORECASE)
df = pd.DataFrame.from_records(shelter.getRecordCriteria({
'$or':[ #Regex isn't allowed in an $in helper so use $or
{"breed": {'$regex': newRegex}}, #pass the regex to the filter
{"breed": {'$regex': chesaRegex}},
{"breed": {'$regex': labRegex}},
],
"sex_upon_outcome": "Intact Female",
"age_upon_outcome_in_weeks\": {"$gte":26.0, "$lte":156.0}
}))https://stackoverflow.com/questions/73967567
复制相似问题