【问题标题】:How to use $in with a Regular Expression with Pymongo如何在 Pymongo 中使用 $in 和正则表达式
【发布时间】:2015-10-28 15:49:07
【问题描述】:

我正在尝试基于 $in 在 mongodb 中聚合一个集合,该集合试图从路径中某处 Log_Dir 包含“/route_sanity/”的所有文档中获取聚合数据。 令人惊讶的是,这个查询不适用于 pymongo。 {请注意,我正在使用 'version by the user}

pipeline=[    
   { '$match': { 'cgdvo_version' : version,'Dut_Name':'yvm','Log_Dir':{ '$in': ['/route_sanity/'] } } },
   { '$group': {          
    '_id':               
        'jid',         
    'PassVEVO': { '$sum': { '$cond' :  [{ '$eq' : ['$Result', 'Pass']}, 1, 0]} },
    'FailVEVO': { '$sum': { '$cond' :  [{ '$eq' : ['$Result', 'Fail']}, 1, 0]} },
    'ErrorVEVO': { '$sum': { '$cond' :  [{ '$eq' : ['$Result', 'Error']}, 1, 0]} },
    'TotalVEVO': { '$sum': 1 }
} }, 
   {'$project':{'FailVEVO':1, 'PassVEVO':1,'ErrorVEVO':1,'TotalVEVO':1,'_id':0}}]
res= smokedb.command('aggregate','jid',pipeline=pipeline)

为了交叉检查,以下查询在 robomongo(mongodb 客户端)中运行良好

db.getCollection('jid').find({cgdvo_version : 'pub-20150614.2',Dut_Name:'yvm',Log_Dir:{ $in: [/route_sanity/] }})

请帮忙!提前致谢。

【问题讨论】:

    标签: regex mongodb mongodb-query pymongo


    【解决方案1】:

    正则表达式有引号,这意味着它被解释为字符串。如果对您的语言语法有疑问,请改用$regex BSON 操作。但是这里只使用re.compile

    pipeline=[    
       { '$match': { 
           'cgdvo_version' : version,
           'Dut_Name':'yvm',
           'Log_Dir':{ 
               '$in': [re.compile('/route_sanity/')] 
           }
       }},
       { '$group': {          
        '_id':               
            'jid',         
        'PassVEVO': { '$sum': { '$cond' :  [{ '$eq' : ['$Result', 'Pass']}, 1, 0]} },
        'FailVEVO': { '$sum': { '$cond' :  [{ '$eq' : ['$Result', 'Fail']}, 1, 0]} },
        'ErrorVEVO': { '$sum': { '$cond' :  [{ '$eq' : ['$Result', 'Error']}, 1, 0]} },
        'TotalVEVO': { '$sum': 1 }
       }}, 
       {'$project':{'FailVEVO':1, 'PassVEVO':1,'ErrorVEVO':1,'TotalVEVO':1,'_id':0}}
    ]
    

    否则:

       { '$match': { 
           'cgdvo_version' : version,
           'Dut_Name':'yvm',
           '$or':[{ 'Log_Dir': { '$regex': 'route_sanity' }}]
       }},
    

    或者因为它们是正则表达式,有多个可能的匹配项,那么只需在此处使用 OR | 操作

       { '$match': { 
           'cgdvo_version' : version,
           'Dut_Name':'yvm',
           'Log_Dir': { '$regex': 'route_sanity|something_else' }
       }},
    

    这样就不需要$in$or

    另请注意,您目前只有一种情况。这些方法允许您使用正则表达式指定多个条件。但是,如果您只需要一个,那么就这样做:

       { '$match': { 
           'cgdvo_version' : version,
           'Dut_Name':'yvm',
           'Log_Dir': { '$regex': 'route_sanity' }
       }},
    

    【讨论】:

    • 感谢您的回复!但是这两种情况都不适合我。 :(
    猜你喜欢
    • 2013-11-20
    • 2017-07-03
    • 2017-08-12
    • 2019-10-15
    • 2014-06-06
    • 2023-04-07
    • 2020-10-26
    • 2011-03-29
    相关资源
    最近更新 更多