【问题标题】:pymongo : find query with regexpymongo:使用正则表达式查找查询
【发布时间】:2019-06-26 17:15:30
【问题描述】:

我正在编写一个 python 脚本来连接到 mongodb 并查询一个集合。

我想找到以cdl 开头的键hp 的值。当我尝试通过 mongo shell 时,此查询成功运行,但通过我的 python 脚本,我看到了错误。

我需要任何转义字符吗?

./pymongoconn.py

File "./pymongoconn.py", line 20

for response in conn.collection.find({"hp": /^cdl/},{"n":1 ,"hp":1 , "_id":0 , "rsid" :1, "v":1}):                                         

^   

SyntaxError: invalid syntax

以下是我的查询:

for response in conn.collection.find(
    {"hp": /^cdl/},
    {"n":1 ,"hp":1 , "_id":0 ,"rsid" :1, "v":1}
):
    print (response)

【问题讨论】:

    标签: python mongodb pymongo


    【解决方案1】:

    使用重新编译:

    import re
    cdl= re.compile("^cdl", re.IGNORECASE)
    for response in conn.collection.find(
      {"hp": cdl},
      {"n":1 ,"hp":1 , "_id":0 ,"rsid" :1, "v":1}
    ):
      print (response)
    

    【讨论】:

      【解决方案2】:

      我认为你的语法对于 pymongo 中的 $regex 略有错误。

      试试:

       conn.collection.find(
         {"hp": {"$regex": "^cdl"}}, 
         {"n":1 ,"hp":1 , "_id":0 ,"rsid" :1, "v":1}
       )
      

      您也可以将$option 添加到$regex 中。如果你想要不区分大小写;

      conn.collection.find({"hp": {"$regex": "^cdl", "$options": "i"}}))
      

      根据 mongo $regex, here,您可以使用所有选项

      【讨论】:

        猜你喜欢
        • 2020-10-26
        • 2011-03-29
        • 2023-03-14
        • 2016-05-17
        • 2020-03-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多