简体   繁体   English

pymongo:使用正则表达式查找查询

[英]pymongo : find query with regex

I am working on a python script to connect to mongodb and query a collection. 我正在使用python脚本连接到mongodb并查询集合。

I want to find the values for key hp that start with cdl . 我想查找以cdl开头的hp的值。 This query successfully runs when I try through mongo shell but through my python script I see the error. 当我尝试通过mongo shell时,此查询成功运行,但是通过我的python脚本,我看到了错误。

Do I need to have any escape characters ? 我是否需要转义字符?

./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

Below is my query : 以下是我的查询:

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

Use re.compile: 使用re.compile:

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)

I think your syntax is slightly wrong for a $regex in pymongo. 我认为您的语法对于pymongo中的$regex有点错误。

Try: 尝试:

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

You could also add in $option into the $regex . 您也可以在$regex添加$option If you wanted case insensitive; 如果要区分大小写;

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

You have all the options available as per mongo $regex , here 您具有每个mongo $regex可用的所有选项, 在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM