$regex not working despite following exactly what the documentation says

Hello all, this is my first time on the forums, so please excuse any mistakes I might make with this post. With that being said, I am currently using pymongo for a small web app which I plan to use to take notes in school. I am attempting to implement a search function to allow me to search for documents containing certain topics.

This is my data inside mongodb atlas:
{"_id":{"$oid":"5f5d3ffc88e588d51ced6193"}, "test_idea":["information1","information2"], "subtopic":"subtopic_test", "test_idea2":["information3"]}

I am querying the ‘subtopic’ field only. The code I am using to query it is:
collection.find({"subtopic": {"$regex": str("/%s/" % query), "$options": 'i'}})

Just to clarify that code a bit, the str("/%s/" % query) portion just adds ‘/’ before and after the query. In spite of this code being almost identical to the docs, it returns nothing. I’ve been stuck on this for several hours now, and I would appreciate any advice I could get.

If you want to see the full code, it is located at: https://repl.it/@emotionbot/jacknotes#database.py

Hi @Jack_Hodge and welcome in the MongoDB Community :muscle: !

You have exactly the right syntax but there is just a little detail :smiley: ! You don’t need the slaches in this type of query because the information that the string is a regex is already in $regex so…

query = 'test'
collection.find_one({"subtopic": {"$regex": query, "$options": 'i'}})

This works for me.


This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.