我在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接收相同的结果。
我将数组转换为如下所示
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
}}
])
你可能不需要使用聚合查询,但无论哪种方式,这个构造都应该是可行的。
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})