Python 带有pymongo和$ne的SyntaxError:null
这是我的代码:Python 带有pymongo和$ne的SyntaxError:null,python,mongodb,pymongo,mongodb-query,Python,Mongodb,Pymongo,Mongodb Query,这是我的代码: #! /usr/bin/python import os from pymongo.connection import Connection from pymongo.master_slave_connection import MasterSlaveConnection database = 'toto' collection = 'logs' master = Connection(host="X.X.X.X", port=27017) slave1 = Connec
#! /usr/bin/python
import os
from pymongo.connection import Connection
from pymongo.master_slave_connection import MasterSlaveConnection
database = 'toto'
collection = 'logs'
master = Connection(host="X.X.X.X", port=27017)
slave1 = Connection(host="X.X.X.X", port=27017)
con = MasterSlaveConnection(master, slaves=[slave1, master])
db = getattr(con,database)
#host_name.append("getattr(db,collection).distinct( 'host_name' )")
#print host_name[1]
hosts = db.logs.distinct( 'host_name' )
services = db.logs.distinct("service_description" , { "service_description" : { $ne : null } } )
#print hosts
print services
我得到了这个错误:
File "./rapport.py", line 23
services = db.logs.distinct("service_description" , { "service_description" : { $ne : null } } )
^
SyntaxError: invalid syntax
为什么我不能在代码中使用“$ne:null”
?我不明白,因为当我直接在mongodb中执行这个查询时,“db.logs.distinct”(“service_description”,{“service_description”:{$ne:null}>),它可以工作
我也试过这个,但不起作用:
services = db.logs.distinct("service_description", { "service_description" : { "$ne" : None } } )
谢谢您的帮助。您需要引用
$ne
并使用None
而不是null。
Pymongo使用dicts作为参数
asdf = "something"
{ asdf: "foo"}
是有效的声明,使用“something”
作为键
如果你将其与
{$ne: "foo"}
解释器需要一个变量名作为第一个条目,$ne
无效
另外,null
在Python中不是预定义的,因此请改用None
结合pymongo中的流体界面,您的查询应该是:
db.logs.find({"service_description": {"$ne" : None}}).distinct('service_description')
谢谢我试图引用$ne并使用None,但它不起作用“services=db.logs.distinct”(“service_description”,{“service_description”:{“$ne:None}})”我得到了这个错误“TypeError:distinct()正好接受2个参数(给定3个)”,这是因为在pymongo中接口更流畅。你需要使用
find().distinct()
,cf.(文档)[你能给我举个例子吗?我是个新手。Thx