这是我的代码:
#! /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"
在我的代码中使用?我不明白,因为当我"db.logs.distinct("service_description" , { "service_description" : { $ne : null } } )"
直接在mongodb中执行此查询时,它可以工作.
我也试过这个,但它不起作用:
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')