【问题标题】:How to query with case insensitivity and partial match in pymongo?如何在pymongo中查询不区分大小写和部分匹配?
【发布时间】:2020-07-27 19:04:47
【问题描述】:

我是 Python 编程新手。我有一个函数,它需要一个集合和一个过滤器列表。

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


我会在 MongoDB 中运行以下查询以获取部分匹配并忽略大小写。

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

我不知道如何将此查询转换为 Python 以获得相同的结果。

【问题讨论】:

  • 这能回答你的问题吗? PyMongo $in + $regex
  • 我试图找到的解决方案有点不同。感谢您的帮助。

标签: python-3.x mongodb pymongo


【解决方案1】:

您可以使用$regex 查询运算符并指定不区分大小写的选项“i”。

基于这些测试文档:

{'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'}

以下 pymongo 语法应该会产生您想要的结果(为方便起见,只需将光标处理为列表)。由于$and 是默认值,因此没有必要。

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)

导致选择以下 2 个文档:

{'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'}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-12
    • 2011-02-09
    • 2017-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多