0

I have this MongoDB query in Python.

    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
        }}
])

I am having difficulty turning this line into a valid Python syntax

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

I tried "$regex" option but we cannot use $regex inside $in. I also tried converting the array elements into the string and escaping the slashes as shown below.

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

I want to know how I can turn that MongoDB query into valid python syntax and receive the same results using PyMongo.

2 Answers2

0

I converted the array as shown below

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
    }}
])

Reference : regex – Tools for representing MongoDB regular expressions¶

0

You probably don't need to to use an aggregate query, but either way this construct should work:

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})
Belly Buster
  • 8,224
  • 2
  • 7
  • 20