0

I am new to Python programming. I have a function that takes a collection, and a list of filters.

poolFilter = [{"ip": "7.98"}, {"partition": "common"}]

searchCollection("pools", poolFilters)

def searchCollection(collection, filters):
    c = db[collection] 
    results = c.find({"$and" : filters},{'_id': False})  
    return results


I would run the following query in MongoDB for a partial match and ignore case.

db.getCollection('f5.pools').find({$and : [{"ip": /7.98/i}, {"partition": /Common/i}]})

I am not aware on how to translate this query into Python for same results.

  • 1
    Does this answer your question? [PyMongo $in + $regex](https://stackoverflow.com/questions/19867389/pymongo-in-regex) – D. SM Apr 14 '20 at 23:30
  • It was little bit different for the solution I was trying to find. Thanks for the help. – MoondaKamina Apr 15 '20 at 13:39

1 Answers1

0

You can use the $regex query operator and specify the case insensitive option "i".

Based on these test docs:

{'ip': '10.2.7.98',
 'other': 'another field',
 'partition': 'this is coMMon',
 'pools': 'test doc 1'}
{'ip': '7.98.202.101',
 'other': 'another field',
 'partition': 'Common partition',
 'pools': 'test doc 2'}
{'ip': '7.9.202.101',
 'other': 'another field',
 'partition': 'Cmmon partition',
 'pools': 'test doc 3'}
{'ip': '7.7.98.122',
 'other': 'another field',
 'partition': 'Como partition',
 'pools': 'test doc 4'}

The following pymongo syntax should produce your desired results (just processing the cursor as a list for convenience). Since $and is the default it is not necessary.

ip_value = '7.98'
partition_value = 'common'

ip_filter = {'ip': {'$regex': ip_value, "$options": "i"}}
partition_filter = {'partition': {'$regex': partition_value, "$options": "i"}}

query = {}
query.update(ip_filter)
query.update(partition_filter)
projection = {'_id': False}

mlist1 = list(coll.find(query, projection))

for mdoc in mlist1:
    pprint.pprint(mdoc)

Results in selecting the following 2 documents:

{'ip': '10.2.7.98',
 'other': 'another field',
 'partition': 'this is coMMon',
 'pools': 'test doc 1'}
{'ip': '7.98.202.101',
 'other': 'another field',
 'partition': 'Common partition',
 'pools': 'test doc 2'}
DaveStSomeWhere
  • 2,475
  • 2
  • 22
  • 19