如何使用 PyMongo 在 python 中执行通配符搜索 mongoDB

How to perform wildcard searches mongoDB in python with PyMongo

我有一个文档,例如:

{'my_key':  '2019-carbeureter'}

我要搜索“2019

db.collection.find({'my_key': query_string } # isn't working with the following

query_string = "/2019/"   # doesn't work
query_string = r"/2019/"  # same thing
query_string = ".*2019.*" # doesn't work

这个其他 SO 问题在原生 mongoDB 中解决了它, 但是我如何使用 pymongo 在 Python 中执行此操作? How to query MongoDB with "like"?

db.collections.find({'my_key': <str>}) # Isn't going to work as a bare str

您需要定义一个对象 添加一个 '$regex' operator/key 到对象 该值是熟悉的正则表达式样式:'.*2019.*'

query_string = {'$regex': '.*2019.*'}
results = db.collections.find({'my_key': query_object})

或完全写成:

results = db.collections.find({'my_key': {'$regex': '.*2019.*'}})

您可以使用“$regex”或者另一个选项是使用 re 模块

import re

pattern = re.compile('2019')

db.collection.find({'my_key': pattern })