带有pymongo和$ ne:null的SyntaxError

 当王子爱上灰姑娘 发布于 2023-02-10 10:45

这是我的代码:

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

谢谢你的帮助.

1 个回答
  • 您需要引用$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')
    

    2023-02-10 10:50 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有