3

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.

2 Answers2

3

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)

4J41
  • 5,005
  • 1
  • 29
  • 41
  • Please note that I'm using Python, not Mongo shell. $ is not Python syntax. –  Sep 25 '16 at 03:57
  • 1
    Oh sorry about that, looks like your last line actually works, it just separates upper and lowercase letters. :) –  Sep 25 '16 at 03:58
  • @Gabriel : if you want case insensitive search, please add '$options':'i'... You can see the syntax in my answer... – 4J41 Sep 25 '16 at 04:03
  • 1
    Yes, I saw it, thank you. It just had some issues and there was a \u200c\u200b between the '$options' and the : and it didn't get it. But I re-typed that part and now it works perfectly. Thanks again! –  Sep 25 '16 at 04:06
0

$text

You can perform a text search using $text & $search. You first need to set a text index, then use it:

$ db.docs.createIndex( { title: "text" } )
$ db.docs.find( { $text: { $search: "search_term" } } )

$regex

You may also use $regex, as answered here: https://stackoverflow.com/a/10616781/641627

$ db.users.findOne({"username" : {$regex : ".*son.*"}});

Both solutions compared

... The regular expression search takes longer for queries with just a few results while the full text search gets faster and is clearly superior in those cases.

Community
  • 1
  • 1
alexbt
  • 16,415
  • 6
  • 78
  • 87
  • The $ is invalid syntax in Python. And if I remove it, I get a NameError: name 'title' is not defined message. –  Sep 25 '16 at 03:55
  • And how do you insert a variable into the regex string? That's basically the point of my post. –  Sep 25 '16 at 03:55
  • in python, you'd put the $ characters in quotes, I don't see what wouldn't work – alexbt Sep 25 '16 at 03:59