2

I have a document such as:

{'my_key':  '2019-carbeureter'}

I want to search for '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

This other SO question addresses it in native mongoDB, but how do I do this in Python using pymongo? How to query MongoDB with "like"?

Jordan Stefanelli
  • 1,446
  • 1
  • 13
  • 13

2 Answers2

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

You need to define an object add a '$regex' operator/key to the object the value is then the familiar regex style: '.*2019.*'

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

or written fully as:

results = db.collections.find({'my_key': {'$regex': '.*2019.*'}})
Jordan Stefanelli
  • 1,446
  • 1
  • 13
  • 13
1

You can use '$regex' or another option is to use re module

import re

pattern = re.compile('2019')

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

Community
  • 1
  • 1
oktogen
  • 391
  • 2
  • 5