我有一个文档,例如:
{'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"?
答案 0 :(得分:0)
db.collections.find({'my_key': <str>}) # Isn't going to work as a bare str
您需要定义一个对象
向对象添加“ $ regex”运算符/键
该值就是熟悉的正则表达式样式:'.*2019.*'
query_string = {'$regex': '.*2019.*'}
results = db.collections.find({'my_key': query_object})
或完全写为:
results = db.collections.find({'my_key': {'$regex': '.*2019.*'}})
答案 1 :(得分:0)
您可以使用'$ regex'或另一种选择是使用re module
重新导入
pattern = re.compile('2019')
db.collection.find({'my_key':pattern})