Find documents which contain a particular value - Mongo, Python
<p>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:</p>

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

<p>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.</p>

<h3>$text</h3>

<p>You can perform a text search using <code>$text</code> &amp; <code>$search</code>. You first need to set a text index, then use it:</p>

<pre><code>$ db.docs.createIndex( { title: "text" } )
$ db.docs.find( { $text: { $search: "search_term" } } )
</code></pre>

<h3>$regex</h3>

<p>You may also use <code>$regex</code>, as answered here: <a href="http://stackoverflow.com/a/10616781/641627">http://stackoverflow.com/a/10616781/641627</a></p>

<pre><code>$ db.users.findOne({"username" : {$regex : ".*son.*"}});
</code></pre>

<h3>Both solutions compared</h3>

<ul>
<li><a href="https://dzone.com/articles/mongodb-full-text-search-vs" rel="nofollow">Full Text Search vs. Regular Expressions</a></li>
</ul>

<blockquote>
  <p>... 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.</p>
</blockquote>

python mongodb