Gabriel Gabriel - 2 months ago 6
Python Question

Find documents which contain a particular value - Mongo, Python

I'm trying to add a search option to my website but it doesn't work. I looked up solutions but they all refer to using an actual string, whereas in my case I'm using a variable, and I can't make those solutions work. Here is my code:

cursor = source.find({'title': search_term}).limit(25)
for document in cursor:
result_list.append(document)


Unfortunately this only gives back results which match the search_term variable's value exactly. I want it to give back any results where the title contains the search term - regardless what other strings it contains. How can I do it if I want to pass a variable to it, and not an actual string? Thanks.

Answer

You can use $regex to do contains searches.

cursor = collection.find({'field': {'$regex':'regular expression'}})

And to make it case insensitive:

cursor = collection.find({'field': {'$regex':'regular expression', '$options'‌​:'i'}})

Please try cursor = source.find({'title': {'$regex':search_term}}).limit(25)

Comments