首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >MangoDB使用JavaScript模式和$in算子

MangoDB使用JavaScript模式和$in算子
EN

Stack Overflow用户
提问于 2022-10-06 00:33:37
回答 2查看 54关注 0票数 0

尝试用Pymongo驱动程序创建一个MongoDB查询,该驱动程序搜索数据库以查找一些狗品种,但由于数据质量不同,我需要进行模式匹配。我知道我不能在$in样式的查询中使用Regex,所以我使用JS模式。

到目前为止,我有这样的看法:

代码语言:javascript
复制
df = shelter.getRecords({
    "breed": {"$in": [/labrador/i, /chesa/i, /newfound/i]}
    })

但我有语法错误。命令似乎在shell....is中工作,这是Pymongo的一个限制吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-10-06 20:58:00

你可以像这样用"$regex"

注:您的pymongo查询筛选器可以是python字典,比如{'breed': {'$regex': '(labrador)|(chesa)|(newfound)', '$options': 'i'}}

代码语言:javascript
复制
db.shelter.find({
  "breed": {
    "$regex": "(labrador)|(chesa)|(newfound)",
    "$options": "i"
  }
})

示例输出:

代码语言:javascript
复制
[
  {
    "_id": 21,
    "breed": "Chesapeake Retriever"
  },
  {
    "_id": 80,
    "breed": "Newfoundland"
  }
]

mongoplayground.net上试一试。

票数 0
EN

Stack Overflow用户

发布于 2022-10-12 01:56:07

最后这是我的混合方案..。

代码语言:javascript
复制
           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}
           }))
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73967567

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档