2017-08-05 77 views
1

我已经研究过这个,但是找不到为什么我正在尝试不工作,并且会警告我对Python有点新,对MongoDB也很新。我有一个使用JSON的推文的mongo数据库,我试图通过Python和pymongo进行查询。我想为包含“IP”的所有推文返回“text”和“created_at”字段。在pymongo中查询“like”

我曾尝试以下,我这样做是通过终端时完美的作品:

db.tweets.find({text:/IP/},{text:1,created_at:1}) 

在Python,实验我发现,我需要把引号之间的字段名之后。我已经得到了以下类似的查询工作:

cursor = db.tweets.find({'created_at':"Thu Apr 28 09:55:57 +0000 2016"},{'text':1,'created_at':1}) 

但是当我尝试:

db.tweets.find({"text": /.*IP.*/},{'text':1,'created_at':1}) 

cursor = db.tweets.find({'text':/IP/},{'text':1,'created_at':1}) 

我得到一个

'SyntaxError: invalid syntax' at the "/IP/" part of the code. 

我使用mongo 3.4.6和python 3.5.2

回答

2

Python对于JavaScript等正则表达式没有特殊的语法。

使用re

您需要编译正则表达式re module

import re 

rgx = re.compile('.*IP.*', re.IGNORECASE) # compile the regex 

cursor = db.tweets.find({'text':rgx},{'text':1,'created_at':1})

,如果你想匹配iPIpip也可以使用re.IGNORECASE作为标志。如果你不想要,你可以删除re.IGNORECASE部分。

使用'$regex'符号

或者,您可以指定要与正则表达式的工作:

cursor = db.tweets.find({'text':{'$regex':'IP'}},{'text':1,'created_at':1})