2013-12-16 2 views
4

이 내 코드입니다 :

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

내가 왜 내 코드에서 "$ne : null"를 사용할 수 없습니다

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

나는이 오류가있어? 나는이 쿼리를 실행할 때 mongodb에서 직접 "db.logs.distinct("service_description" , { "service_description" : { $ne : null } })"을 실행하기 때문에 이해하지 못한다.

나는이 시도했지만 작동하지 않습니다 : 당신의 도움에 대한

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

감사합니다.

답변

5

$ne을 인용하고 null 대신 None을 사용해야합니다. Pymongo는 dicts를 매개 변수로 사용합니다.

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

은 유효한 선언이며 "something"을 키로 사용합니다.

당신은

{$ne: "foo"} 

와 인터프리터가 첫 번째 항목으로 변수 이름을 기대하는 비교하면, 그리고 $ne가 잘못되었습니다.

또한 null은 파이썬에서 미리 정의되지 않으므로 대신 None을 사용하십시오.

pymongo에서 유체 인터페이스와 결합

, 쿼리가 있어야한다 :

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

감사합니다. 나는 $ ne를 인용하고 None을 사용하려고했으나 작동하지 않는다 ""service = db.logs.distinct ("service_description", { "service_description": { "$ ne": None}}) "이 오류가 발생했습니다"TypeError : distinct()는 정확히 2 개의 인수 (3이 주어진다.) " –

+0

pymongo에서 인터페이스가 더 유창하기 때문이다. 'find () .distinct ()', cf.를 사용해야합니다. (문서) [http://api.mongodb.org/python/current/api/pymongo/collection.html?highlight=distinct#pymongo.collection.Collection.distinct] –

+0

예를 들어 주시겠습니까? 나는 초보자입니다. 고마워 –