Search code examples
javascriptregexmongodbcursormongodb-query

Searching for a specific string within a mongodb database


I have the following code:

collection.find({title:"foo"}, {title:1, _id:0})

that returns

{title: "foo"}

but when I try:

str = "foo";
collection.find({title:str}, {title:1, _id:0})

I don't get any results back.

All of the examples I've found on stackoverflow use hardcoded strings. How can I search for a string that's constantly being changed within a mongodb database?


Solution

  • var str = "foo";
    var query = {title: str};
    collection.find(query, {title:1, _id:0})
    

    Query to find any word containing str:

    collection.find({title : { $regex : str }}, {title:1, _id:0})