【问题标题】:How to do a case-insensitive regex search of mongodb? [duplicate]如何对mongodb进行不区分大小写的正则表达式搜索? [复制]
【发布时间】:2019-03-11 22:46:07
【问题描述】:

我正在尝试从以下mongodb数据库中读取数据并遇到几个问题,有人可以提供指导吗?

  1. 遇到以下错误,如何解决?

  2. 有没有办法通过正则表达式进行不区分大小写的搜索,我有"\%train\%"如下,不确定这是否正确

from pymongo import MongoClient
import os,pymongo
dbuser = os.environ.get('muser', 'techauto1')
dbpass = os.environ.get('mpwd', 'techpass')
uri = 'mongodb://{dbuser}:{dbpass}@machine.company.com:27017/techautomation'.format(**locals())
client = MongoClient(uri)
db = client.techautomation.tech_build_audit
try:
  #db.tech_build_audit
  myCursor = db.collection.find({"chip" : "4377","branch" : "\%train\%"}).sort({"_id":-1})
  print myCursor

except pymongo.errors.AutoReconnect, e:
  print e

错误:

Traceback(最近一次调用最后一次):

文件“parseplist.py”,第 11 行,在

myCursor = db.collection.find({"chip" : "4377","branch" : "%peaceB%"}).sort({"_id":-1})

文件“/Library/Python/2.7/site-packages/pymongo/cursor.py”,第 703 行,排序 keys = helpers._index_list(key_or_list, direction)

文件“/Library/Python/2.7/site-packages/pymongo/helpers.py”,第 52 行,在 _index_list 中

raise TypeError("如果没有指定方向,"

TypeError: 如果没有指定方向,key_or_list 必须是 list 的一个实例

更新:

由于错误,我无法验证正则表达式是否有效,我该如何修复错误?

【问题讨论】:

    标签: python pymongo


    【解决方案1】:

    您可以将 pythons re 库用于正则表达式,将re.IGNORECASE 用于您的第二个问题,如下所示:

    import re
    
    ### rest of your code
    regx = re.compile("^foo", re.IGNORECASE)
    myCursor = db.collection.find({"chip" : "4377","branch" : regx}).sort({"_id":-1})
    print myCursor
    

    关于您更新的问题:

    这是另一个问题,它是关于使用 sort() 和 pymongo,你可以看到答案 here

    简而言之,您应该像这样使用.sort().sort([("_id", -1)])

    【讨论】:

    • 错误@TypeError: if no direction is specified, key_or_list must be an instance of list仍然存在
    • @user2125827 那是另一个问题,它是关于在 pymongo 中使用 sort(),你可以看到答案 here 简而言之你应该像这样使用.sort().sort([("_id", -1)])
    • 我在回答中添加了评论
    • 实际上没有工作,sort("_id", 1) 工作但打印myCursor 不打印任何值,我如何打印这些值?
    • @user2125827 我猜你的数据库查询结果是空的!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-03
    • 1970-01-01
    • 2011-04-22
    • 1970-01-01
    相关资源
    最近更新 更多