Gabriel Gabriel - 1 year ago 88
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:

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 Source

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)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download