python 实现mongodb查询时不区分大小写
由于一些原因,在mongodb中的数据表存储的都是小写的,但是现在发现和别的业务对接查询时传的参数偶尔会出现大写的情况,这种情况会导致查询结果为空,因此查阅了一些资料,可以使用正则表达式的方式实现:
MongoDB中数据如下:
{'_id': 1.0, 'item': 'ABC', 'price': 180, 'sizes': ['S', 'M', 'XL']}
{'_id': 2.0, 'item': 'EFG', 'price': Decimal128('120'), 'sizes': []}
{'_id': 3.0, 'item': 'IJK', 'price': Decimal128('160'), 'sizes': 'M'}
{'_id': 4.0, 'item': 'LMN', 'price': Decimal128('10')}
{'_id': 5.0, 'item': 'XYZ', 'price': Decimal128('5.75'), 'sizes': None}
{'_id': 7.0, 'item': 'ABC', 'price': 180, 'sizes': ['S', 'M', 'XL']}
查询示例为:
import re
db = MongoConfig()
table = db['inventory2']
it = 'aBc'
name = '^%s$' % it
re_name = re.compile(name, re.IGNORECASE)
re_name
result = table.find({"item": re_name})
for re in list(result):
print(re)
查询结果为:
{'_id': 1.0, 'item': 'ABC', 'price': 180, 'sizes': ['S', 'M', 'XL']}
{'_id': 7.0, 'item': 'ABC', 'price': 180, 'sizes': ['S', 'M', 'XL']}
同样的,应该用到聚合函数中:
data = table.aggregate([
{
'$match': {"item": re_name}
},
# {'$project': {'_id': 0}
# }
])