SyntaxError with pymongo and $ ne: null

this is my code:

#! /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

I got this error:

File "./rapport.py", line 23
    services = db.logs.distinct("service_description" , { "service_description" : { $ne : null } } )
                                                                                    ^
SyntaxError: invalid syntax

Why can't I use "$ne : null"in my code? I do not understand, because when I execute this request "db.logs.distinct("service_description" , { "service_description" : { $ne : null } } )"directly in mongodb, it works.

I also tried this, but it does not work:

services = db.logs.distinct("service_description", { "service_description" : { "$ne" : None } } )

Thank you for your help.

+4
source share
1 answer

You need to quote $neand use Noneinstead of null. Pymongo uses dicts as parameters.

asdf = "something"
{ asdf: "foo"} 

is a valid declaration using "something"as a key.

If you compare it to

{$ne: "foo"}

, $ne .

, null Python, None.

pymongo, :

db.logs.find({"service_description": {"$ne" : None}}).distinct('service_description')
+5

All Articles