蟒蛇逃脱美元符号

0 python mongodb

我很难理解这种语法有什么问题:

from pymongo import MongoClient

client = MongoClient('localhost', 27017)
db = client.monitor
#cursor = db.monitoring_logs.find({"widget": "56dfed49a2988d9019000585;"})
cursor = db.monitoring_logs.find({"widget": {$in:["56dfed49a2988d9019000585;","56d58f5b1dc95f54460002f6;"]}})
print (cursor.count()) 
Run Code Online (Sandbox Code Playgroud)

错误信息:

C:\Users\Nir.Regev\Anaconda3\python.exe C:/Users/Nir.Regev/PycharmProjects/anomaly/get_mongo_data.py
  File "C:/Users/Nir.Regev/PycharmProjects/anomaly/get_mongo_data.py", line 6
    cursor = db.monitoring_logs.find({"widget": {$in:["56dfed49a2988d9019000585;","56d58f5b1dc95f54460002f6;"]}})
                                                 ^
SyntaxError: invalid syntax

Process finished with exit code 1
Run Code Online (Sandbox Code Playgroud)

它是美元符号 ($),如果是,如何解决这个问题?

sro*_*and 7

您需要在 Python 中的任何特殊字符串周围加上引号(在本例中为 '$in') - 您可能正在查看使用 javascript 编写的 Mongo 文档,而不是为 Python 客户端编写的 pymongo 客户端文档(我也做过同样的事情 ;) )。

from pymongo import MongoClient

client = MongoClient('localhost', 27017)
db = client.monitor
#cursor = db.monitoring_logs.find({"widget": "56dfed49a2988d9019000585;"})
cursor = db.monitoring_logs.find({"widget": {'$in': ["56dfed49a2988d9019000585;","56d58f5b1dc95f54460002f6;"]}})
print (cursor.count()) 
Run Code Online (Sandbox Code Playgroud)