我已经对此进行了研究,但找不到为什么我正在尝试的方法不起作用,并且会警告我对 python 有点陌生,对 mongodb 非常陌生。我有一个 JSON 格式的 mongo 推文数据库,我试图通过 Python 和 pymongo 进行查询。我想为所有包含“IP”的推文返回“text”和“created_at”字段。
我已经尝试了以下方法,当我通过终端执行此操作时效果很好:
db.tweets.find({text:/IP/},{text:1,created_at:1})
Run Code Online (Sandbox Code Playgroud)
在 Python 中,经过试验我发现我需要将字段名称放在引号之间。我得到了以下类似的查询:
cursor = db.tweets.find({'created_at':"Thu Apr 28 09:55:57 +0000 2016"},{'text':1,'created_at':1})
Run Code Online (Sandbox Code Playgroud)
但是当我尝试:
db.tweets.find({"text": /.*IP.*/},{'text':1,'created_at':1})
Run Code Online (Sandbox Code Playgroud)
或者
cursor = db.tweets.find({'text':/IP/},{'text':1,'created_at':1})
Run Code Online (Sandbox Code Playgroud)
我得到一个
'SyntaxError: invalid syntax' at the "/IP/" part of the code.
Run Code Online (Sandbox Code Playgroud)
我正在使用 mongo 3.4.6 和 python 3.5.2