蟒蛇逃脱美元符号

时间:2016-03-15 16:41:37

标签: 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()) 

错误消息:

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

是美元符号($),如果是这样,怎么绕过这个?

1 个答案:

答案 0 :(得分:4)

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

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())