【问题标题】:How to write this MongoDB query in a valid way?如何以有效的方式编写此 MongoDB 查询?
【发布时间】:2020-08-27 12:55:41
【问题描述】:

我在 Python 中有这个 MongoDB 查询。

    results = collection.aggregate([
    {
        "$match": {
            "monitor": {
                "$in": [/\/tcp/,/\/http$/,/\/https_443$/,/\/https$/,/\/http_head_f5$/,/\/https_head_f5$/,/\/icmp$/]
            }
        }
    },
    {
        "$project": {
            "_id": 0,
            "name": 1,
            "partition": 1,
            "fullPath": 1,
            "type": 1,
            "loadBalancingMode": 1,
            "monitor": 1,
            "f5ip": 1,
            "poolstatus": 1
        }}
])

我很难将此行转换为有效的 Python 语法

"$in": [/\/tcp/,/\/http$/,/\/https_443$/,/\/https$/,/\/http_head_f5$/,/\/https_head_f5$/,/\/icmp$/]

我尝试了“$regex”选项,但我们不能在 $in 中使用 $regex。 我还尝试将数组元素转换为字符串并转义斜杠,如下所示。

"$in": ["\/\/tcp\/","\/\/http$/"]

我想知道如何将 MongoDB 查询转换为有效的 python 语法并使用 PyMongo 接收相同的结果。

【问题讨论】:

标签: python mongodb pymongo


【解决方案1】:

我把数组转换成如下图

options = ['tcp', 'http$', 'https_443$', 'https$', 'http_head_f5$', 'https_head_f5$', 'icmp$']
regex_options = []

for option in options:
    pattern = re.compile(option)
    regex = bson.regex.Regex.from_native(pattern)
    regex_options.append(regex)

results = collection.aggregate([
{
    "$match": {
        "monitor": {
            "$in": regex_options
        }
    }
},
{
    "$project": {
        "_id": 0,
        "name": 1,
        "partition": 1,
        "fullPath": 1,
        "type": 1,
        "loadBalancingMode": 1,
        "monitor": 1,
        "f5ip": 1,
        "poolstatus": 1
    }}
])

参考:regex – Tools for representing MongoDB regular expressions¶

【讨论】:

    【解决方案2】:

    您可能不需要使用聚合查询,但无论哪种方式,此构造都应该有效:

    results= db.collection.find({'monitor': {'$regex': 'tcp|http$|https_443$|https$|http_head_f5$|https_head_f5$|icmp$'}},
                                {'_id': 0, 'name': 1, 'partition': 1, 'fullPath': 1, 'type': 1, 'loadBalancingMode': 1,
                                 'monitor': 1, 'f5ip': 1, 'poolstatus': 1})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多